繁体   English   中英

如何将以下三个Laravel雄辩查询合并为一个?

[英]How to combine following three Laravel Eloquent Queries into one?

向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。 我想要一个包含所需帖子的结果,将上一个帖子包含在所需帖子中,将下一个帖子包含在所需帖子中

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

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

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('id', '>', $postId)where('id', '<', $postId)合并到此单行中,其中statemenet => where('id', '!=', $postId)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM