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

How to use Laravel Eloquent with LIKE statement in array list?

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

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

我怎样才能

$list  = Data::where($conditions)->where('cuisine','LIKE','%'.$cuisine.'%')->get();

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

if($cuisine) $conditions['cuisine'] = $cuisine;

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

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

嗯,你可以分几个部分来做:

$query = Data::where($conditions);
if($cuisine) {
    $query->where('cuisine','LIKE','%'.$cuisine.'%');
}
$list = $query->get();

当然,您可以通过创建 an array with this format:

[['column1', 'like', '%' . $filter1 . '%'], ['column2', 'like', '%' . $filter2 . '%']]

例如:

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

文档中的另一个示例:

You may also pass an array of conditions to the where function:

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

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

更新

您刚刚更新了您的问题并表示您只想对 $cuisine 使用 like。在这种情况下,您可以使用闭包:

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

或者您可以使用 when():

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

你可以这样做,

$query = DB::table('data');

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

if($category) {
    $query->where('category','LIKE','%'.$category.'%');
}
if($cuisine) {
    $query->where('cuisine','LIKE','%'.$cuisine.'%');
}
if($veg) {
    $query->where('veg','LIKE','%'.$veg.'%');
}
if($trending) {
    $query->where('trending','LIKE','%'.$trending.'%');
}
if($time) {
    $query->where('time','LIKE','%'.$time.'%');
}

$list = $query->get();

希望您能理解。

为什么不将默认值指定为空值,因为它会在所有情况下传入 LIKE

$conditions['cuisine']= (isset($cuisine)&&$cuisine)) ? $cuisine : '';

嗯,您必须将查询分配给某个变量:

    $query = Data::where($conditions);
     if($cuisine) { 
    $query = $query->where('cuisine','LIKE','%'.$cuisine.'%'); 
    } 
$list = $query->get();