0

向 Laravel 和 mysql 专家快速提问,我有以下三个查询:-

// Only Can use slug here
$post = Post::whereSlug($slug)->with(['category', 'author'])->first();


$prevPost = Post::where('id', '<', $post->id)
            ->select('id', 'title', 'slug')
            ->orderBy('id', 'desc')
            ->first()

$nextPost = Post::where('id', '>', $postId)
            ->select('id', 'title', 'slug')
            ->orderBy('id')
            ->first()

有什么办法可以将所有三个查询合并为一个。我想将所有三个查询合并为一个,对于最后两个查询,我需要 $post->id。我想要一个包含所需帖子的结果,上一个帖子到所需帖子,下一个帖子到所需帖子

4

2 回答 2

1

没有真正的 Eloquent 方法可以将所有这些查询组合成一个查询。您可以使用 Fluent 原始查询以及一些棘手的窗口函数,但是编写这些函数会很耗时,并且取决于您特定的 SQL 类型。

于 2018-02-27T06:00:48.263 回答
0

最好的方法是使用某种范围来实现:

public function scopeOfId($query, $id, $operator, $orderBy = "asc") {
   $query->where('id', $operator, $id)
        ->select('id', 'title', 'slug')
        ->orderBy('id', $orderBy)
}

然后你真的会称它Post::ofId(5, "<")Post::ofId(5, "<", "desc")任何组合。也可以合并到这个单 where statemenet =>where('id', '>', $postId)中。where('id', '<', $postId)where('id', '!=', $postId)

于 2018-02-27T05:24:50.053 回答