将 SQL 搜索查询翻译成 Eloquent 查询

Translate SQL Search Query to Eloquent Query

我想进行以下查询。

select * from `items` 
    where (`item_name` LIKE 'foo' or `item_description` LIKE 'foo') 
    and `item_type` = 'type1' 

翻译成Eloquent。我提出了以下声明:

$items = Item::where('item_type', '=', 'type1')
    ->orWhere('item_name','LIKE','%'.$q.'%')
    ->orWhere('item_description','LIKE','%'.$q.'%')
    ->sortable(['id' => 'desc'])
    ->paginate(10);

在上面的代码片段中,$q 将是 foo(这是一个搜索查询)。

问题是这 return 不是我想要的,因为它还有 return 属于另一个 item_type 的项目,而不是我的 type1例如。

如何在 Eloquent 查询中翻译上述 SQL 查询,以便它仅 return 包含 foo 且类型为 Type1 只有?

试试这个。你需要一个嵌套的 where 闭包:

$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);