I would like to have the following query.
select * from `items`
where (`item_name` LIKE 'foo' or `item_description` LIKE 'foo')
and `item_type` = 'type1'
Translated into Eloquent. I have come up with the following statement:
$items = Item::where('item_type', '=', 'type1')
->orWhere('item_name','LIKE','%'.$q.'%')
->orWhere('item_description','LIKE','%'.$q.'%')
->sortable(['id' => 'desc'])
->paginate(10);
In the above snippet, $q
will be foo
(it's a search query).
The problem is that this does not return exactly what I want since it also returns items that belong to another item_type
instead of the type1
in my example.
How can I translate the above SQL query in an Eloquent query so that it only returns the items which contain foo
and which are of type Type1
only?
Try this. You need a nested where
closure:
$items = Item::where('item_type', '=', 'type1')
->where(function($query) use ($q) {
$query->where('item_name','LIKE','%'.$q.'%')
->orWhere('item_description','LIKE','%'.$q.'%');
})
->sortable(['id' => 'desc'])
->paginate(10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.