如何将此代码转换为Laravel(雄辩):
Component1
答案 0 :(得分:3)
尝试一下:
假设帖子是您的模特
$posts = Post::where('is_public', 1);
if (isset($date)) {
$posts->where('created_at', '>', $date);
}
if (isset($search)) {
$posts->where(function($query) use ($search) {
$query->where('title', 'like', "%'.$search.'%")
->orWhere('body', 'like', "%'.$search.'%");
});
}
$posts = $posts->get();
答案 1 :(得分:1)
这是示例代码:假设Post是您的模型
$getPosts=Post::query()->where('is_public',1);
$getPosts->when(isset($date),function($q) use ($date){
$q->where('created_at','>',$date);
});
$getPosts->when(isset($search),function($q) use ($search){
$q->where('title','like','%'.$search.'%');
$q->orWhere('body','like','%'.$search.'%');
});
$posts=$getPosts->get();
答案 2 :(得分:0)
您应该尝试以下操作:
$query = Post::where('is_public', '1');
if (isset($date)){ //$date format is '2018-09-01 00:00:00'
$query->where('created_at', '>', $date);
}
if (isset($search)){
$query->whereRaw('title LIKE "%'.$search.'%" OR body LIKE "%'.$search.'%"');
}
$posts = $query->get();