我有一个包含库存产品的数据库。另外,我有很多用户,产品属于不同的用户。因此,我需要编写一个具有多个条件的查询,其中搜索需要在不同的表列中,因此它将是几个->orWhere()
语句。但是搜索需要找到属于同一用户的所有产品。但是,如果我有很多->orWhere()
条件,查询就会开始在其他查询条件匹配的其他用户(“标题”或“ product_number”)下搜索产品。
那么,如何更改我的代码,在哪里可以得到所有带有搜索关键字的产品,而在同一用户下的产品呢?
这是我的代码:
public function searchProduct(Request $search){
$search_item = $search->search;
$user = User::where('id', Auth::user()->id)->first();
$inventory = Inventory::where('client_id', $user->client_id)
->where('product_number', 'like', "%{$search_item}%")
->orWhere('title', 'like', "%{$search_item}%")
->orWhere('other_product_numbers', 'like', "%{$search_item}%")
->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
->paginate(50);
$cleint_currency = SettingsClientCurrency::where('client_id', $user->client_id)->first();
$inventory_products = Inventory::where('client_id', $user->client_id)->with('orderInRecord')->get();
$inventory_total = 0;
foreach ($inventory_products as $product) {
$ordersin = $product->orderInRecord;
foreach ($ordersin as $orderin) {
$inventory_total += $orderin['price'] * $orderin['units'];
}
}
return view('layouts.inventory.inventory')
->with('inventory', $inventory)
->with('inventory_total', $inventory_total)
->with('cleint_currency', $cleint_currency)
->with('user', $user);
}
您可以在第二个where子句中使用两个where子句和一个回调函数。会得到您想要的结果
$inventory = Inventory::where('client_id', $user->client_id)
->where(function ($query) use ($search_item) {
$query->where('product_number', 'like', "%{$search_item}%")
->orWhere('title', 'like', "%{$search_item}%")
->orWhere('other_product_numbers', 'like', "%{$search_item}%");
})
->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
->paginate(50);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句