如何在Laravel中实现不同数据库表的并集



我有两个模型:游戏和帖子

在我的控制器中,我有两个查询来分别获取游戏和帖子:

$posts = Post::with(['comment', 'comment.responsavel', 'responsavel', 'like', 'share'])
->whereIn('posts.responsavel_id', $follow->pluck('seguido_id'))
->OrWhere('posts.responsavel_id', '=', $user->id)
->orderBy('published_at', 'DESC')
->paginate(5);
$games = Game::where(function ($query) use ($arr) {
return $query
->whereIn('time_id', $arr)
->orWhereIn('time_desafiado_id', $arr);
})->where('games.grupo', '!=', 'Desafiado')
->select('games.*', DB::raw('CONCAT ( games.data, " ",games.horario ) as published_at'))
->paginate(5);

在我的应用程序的Feed中,我运行了一个foreach,它遍历了所有游戏和按发布日期排序的帖子(混合(

问题是,在提要中,我有一个分页系统,一次只显示5个项目(张贴分页(,因此游戏在提要的最后一页。

我想知道一种同时将两者混合的方法。

我想通过Eloquent并集方法将两个变量合并为一。问题是,因为它们是具有不同字段的表,所以我不能进行这种联合。

我试着通过加入来做到这一点,但这两个模型被结合在一起,游戏最终被归类为帖子。

饲料分页代码:

@if($posts != null)
{{ $posts->links() }}

我解决了它!

我用一个简单的get替换了代码的分页。

我在帖子数组中添加了所有游戏:

foreach ($games as $game) {
$posts->push($game);
}

之后,我更改了AppServiceProvider.php文件的引导方法,使laravel在Collections中接受分页,而不仅仅是在Queries:中

use IlluminateSupportCollection;
use IlluminatePaginationLengthAwarePaginator;
public function boot()
{
/**
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}

然后,只需要重新排序项目,并直接在Ready Collection中运行分页:

$posts = $posts->sortByDesc('published_at')->paginate(5);

最新更新