Reputation: 389
I have a database with inventory products. Also, I have many users where products belonged to different users.
So I need to write a query with multiple conditions, where search needs to be in different table columns, so it will be a couple of ->orWhere()
statements. But the search needs to find all the products that belonged to the same user. But if I have many ->orWhere()
conditions, query starts searching the products under other users where other queries conditions match ("title" or "product_number").
So how can I change my code, where I can get all products with search keyword where the products under the same user?
Here is my code:
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);
}
Upvotes: 0
Views: 2171
Reputation: 6233
you can use two where clause with a callback function in the second where clause. that will get your desired result
$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);
Upvotes: 2