如何在Laravel Eloquent中使用空参数制作whereIn查询构建器

时间:2019-02-12 13:54:54

标签: php laravel eloquent

我已经在Laravel Eloquent中进行了查询,以便在表中进行搜索。

public function searchContest($search){
    $category = [];
    $area = [];

    if(isset($search['area'])){
        $area = $search['area'];
    }

    if(isset($search['category'])){
        $category = $search['category'];
    }

    $qry = self::whereIn('area',$area)
                ->whereIn('category', $category)
                ->get();
    var_dump($query);
    return;
}

但是有时areacategory为空,whereIn不能使用。我无法在网络上找到任何有效的解决方案。我该如何查询?

3 个答案:

答案 0 :(得分:5)

或者您可以将条件条款用作here

DB::table('table_name')
    ->when(!empty($category), function ($query) use ($category) {
          return $query->whereIn('category', $category);
    })
    ->when(!empty($area), function ($query) use ($area) {
          return $query->whereIn('area', $area);
    })
    ->get();

答案 1 :(得分:1)

$q = self::query();
if (isset($search['area'])) {
  $q->whereIn('area', $search['area']);
}
if (isset($search['category'])) {
  $q->whereIn('category', $search['category']);
}
$qry = $q->get();

答案 2 :(得分:0)

您可以在实体内部使用查询范围

    public function scopeArea($query, $ids)
    {
        if (! $ids) {
            return ;
        }
        return $query->whereIn('area', $ids);
    }

    public function scopeCategory($query, $ids)
    {
        if (! $ids) {
            return ;
        }
        return $query->whereIn('category', $ids);
    }

现在您可以构建查询

    $entity
        ->area($area)
        ->category($category)
        ->get();

https://laravel.com/docs/5.7/eloquent#query-scopes