如果参数为null,则选择all,否则返回specfic item laravel

5lhxktic  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(368)

我计划创建一个过滤器。如果参数为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();
abithluo

abithluo1#

根据条件更新查询生成器对象

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

相关问题