如何在数组列表中使用带有 LIKE 语句的 Laravel Eloquent?

Jij*_*n P 1 laravel eloquent laravel-5.3

我在数组中有一些条件,例如

    $category = Input::get('category');
    $cuisine = Input::get('cuisine');
    $veg = Input::get('veg');
    $trending = Input::get('trending');
    $time = Input::get('time');

    if($category) $conditions['category'] = $category;
    if($cuisine) $conditions['cuisine'] = $cuisine;
    if($veg) $conditions['veg'] = $veg;
    if($trending) $conditions['trending'] = $trending;
Run Code Online (Sandbox Code Playgroud)

我该怎么做

$list  = Data::where($conditions)->where('cuisine','LIKE','%'.$cuisine.'%')->get();
Run Code Online (Sandbox Code Playgroud)

是否可以在此语句中输入 LIKE %

if($cuisine) $conditions['cuisine'] = $cuisine;
Run Code Online (Sandbox Code Playgroud)

问题是,如果我想添加这个 where('cuisine','LIKE','%'.$cuisine.'%') 几个需要更新的区域。在某些情况下,如果没有美食,一切都无法获取

我只想对美食数据执行 LIKE 语句。

Ale*_*nin 5

当然,您可以通过使用以下格式创建数组来做到这一点

[['column1', 'like', '%' . $filter1 . '%'], ['column2', 'like', '%' . $filter2 . '%']]
Run Code Online (Sandbox Code Playgroud)

例如:

$fields = ['category', 'cuisine', 'veg', 'trending', 'time'];

foreach ($fields as $field) {
    if ($request->get($field)) {
        $conditions[] = [$field, 'like', '%' . $request->get($field) . '%'];
    }
}

$list = Data::where($conditions)->get();
Run Code Online (Sandbox Code Playgroud)

文档中的另一个示例:

您还可以将条件数组传递给 where 函数:

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();
Run Code Online (Sandbox Code Playgroud)

https://laravel.com/docs/5.5/queries#where-clauses

更新

您刚刚更新了您的问题,并说您只想将其like用于$cuisine. 在这种情况下,您可以使用闭包:

->where(function($q) use($request) {
    if ($request->cuisine) {
        $q->where('cuisine', 'like', '%' . $request->cuisine . '%');
    }
})
Run Code Online (Sandbox Code Playgroud)

或者你可以使用when()

->when($request->cuisine, function ($q) use ($cuisine) {
    return $q->where('cuisine', 'like', '%' . $request->cuisine . '%');
})
Run Code Online (Sandbox Code Playgroud)