Reputation: 353
How can I implement this in Eloquent?.
select * from product where name like '%value%' and (product_type = product_type_param or product_type_param = 0);
If a product_type_param
value of 0
is supplied, it will select products of all types, taking into account that the name also matched, of course.
My current code:
$result = Product::where( [ ['name', 'like', '%' .
$searchAttributes['name'] . '%'],
['product_type', '=', $searchAttributes['product_type']]]
)->get();
The idea would be something like this (excuse the example, it only shows my intention):
['product_type', '=', $searchAttributes['product_type']] or [$searchAttributes['product_type'] == 0]]
Should I execute a raw query?
Upvotes: 0
Views: 224
Reputation: 2894
You can use a closure function to scope the query
Product::where('name', 'like', '%' . $searchAttributes['name'] . '%')
->where(function($q) use ($searchAttributes) {
$q->where('product_type', $searchAttributes['product_type'])
->orWhere('product_type_param', 0);
})->get();
Upvotes: 1
Reputation: 1153
using orWhere
:
Product::where([
['column','value'],
['another_column','value'],
])->orWhere([
['column','value']
])->get();
Upvotes: 0