如果参数为null,则全选,否则返回特定项目laravel

时间:2018-06-25 17:00:19

标签: mysql sql laravel-5.5

我计划创建一个过滤器。如果参数为null,则返回所有其他返回特定项。

title = "A" and body="B"  --> return all values where title like A & body like B
title = "" and body="B"  -->  return all values where body like B
title = "" and body=""  -->  return all values 

这是我的查询,如何根据我的条件更改此查询

$posts =  Blog::where('title','LIKE',"%{$title}%")
            ->Where('body', 'LIKE',"%{$body}%")
            ->offset($start)
            ->limit($limit)
            ->orderBy($order,$dir)
            ->get();

1 个答案:

答案 0 :(得分:0)

根据您的条件更新查询构建器对象

$posts =  Blog::offset($start)
            ->limit($limit)
            ->orderBy($order,$dir);
if(!empty($title)){
    $posts = $posts->where('title','LIKE',"%{$title}%");
}

if(!empty($body)){
    $posts = $posts->where('body','LIKE',"%{$body}%");
}           
$posts = $posts->get();