我有一个主页上的帖子概述新闻网站。简单的有说服力的集合和分页,没有什么特别的(model = Post)。现在已经添加了一个新的模型(视频),它应该添加到主页上的帖子概述中。
因此,我们的目标是获得一个有说服力的帖子集合和一个有说服力的视频集合(它们彼此不相关),然后将它们组合成一个集合并对它们进行分页。
我环顾四周,尝试了几种方法,但似乎都不起作用。大多数时候,他们说要使用$collection->merge($otherCollection),但这并不管用,因为如果有一个id相同的帖子,id为1的视频就不会显示出来,情况就是这样。
另一种选择是定义关系,但由于它们根本不相关,因此也不会起作用。
我目前所拥有的,只是为了获得这些帖子:
if ($highlighted) {
$posts = Post::where([
['status_id', '=', 4],
['published_at', '<=', Carbon::now()],
['id', '!=', $highlighted->id],
])->latest('published_at')->paginate(14);
} else {
$posts = Post::where([
['status_id', '=', 4],
['published_at', '<=', Carbon::now()]
])->latest('published_at')->paginate(15);
}现在,我想以类似的方式检索视频
$videos = Video::where([
['status_id', '=', 4],
['published_at', '<=', Carbon::now()]
])->latest('published_at')->paginate(15);然后将它们组合成一个雄辩的集合,并对总数进行分页,而不是分别对视频和帖子进行分页
例如:$collected = $videos + $posts,然后是->latest('published_at')->paginate(15)
(为了这篇文章的长度,我没有添加任何我尝试过的例子,因为我觉得这不是一种方法,使用->merge()。我还需要一个雄辩的集合,使用纯DB查询不起作用,除非它可以转换成一个雄辩的集合)
也许使用雄辩的集合是不可能的,而我应该使用查询构建器?
任何反馈/帮助都是非常感谢的。(请随时询问额外的代码/信息)
发布于 2019-04-01 15:43:56
感谢这里发布的评论和答案,我设法找到了一个似乎可行的解决方案:
为了检索数据,我执行了以下操作:
$posts = Post::where([
['status_id', '=', 4],
['published_at', '<=', Carbon::now()]
])->get();
$videos = Video::where([
['status_id', '=', 4],
['published_at', '<=', Carbon::now()]
])->get();
$collected = $videos->union($posts)->sortByDesc('published_at');正如在关于这个问题的评论中所提到的:https://stackoverflow.com/a/30421846/4666299,我使用https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e进行分页。
这样我就可以这样做了:
$items = (collect($collected))->paginate(15);现在我有了一个可以在Blade中循环的集合。谢谢你的帮助!
发布于 2019-03-29 07:23:42
您可以发送两个不同的查询,将两个结果合并到一个Illuminate\Support\Collection中,然后使用sortBy('published_at'),然后使用skip(($numPage - 1) * $perPage)和limit($perPage)进行分页。
如果有帮助,请告诉我
https://stackoverflow.com/questions/55408192
复制相似问题