查询Laravel雄辩的结果时如何使用多个参数

时间:2018-10-30 21:16:29

标签: php laravel eloquent

我正在通过Laravel雄辩的控制器查询数据库帖子,想先过滤帖子然后分页。

$filter = ['author_id' => $id, 'status' => 'live', 'type' => $type];
$posts = Post::where($filter)->orderBy('id','desc')->get();
$posts = Post::paginate(1, ['*'], 'page', $page);

return $posts;

当然,目前仅会分页。如何合并两个$posts,以便对过滤后的结果进行分页?

谢谢!

2 个答案:

答案 0 :(得分:2)

就像链接这些方法一样简单:

$posts = Post::where($filter)
    ->orderBy('id','desc')
    ->paginate(1, ['*'], 'page', $page);

答案 1 :(得分:0)

您还可以像这样简化解决方案,这将变得更加灵活。

$filter = ['author_id' => $id, 'status' => 'live', 'type' => $type];

$posts = new Post();
$posts = $posts->where($filter);
$posts = $posts->orderBy('id','desc');
$posts = $posts->paginate(1, ['*'], 'page', $page);

return $posts;