Laravel-联合+分页? [英] Laravel - Union + Paginate at the same time?

查看:114
本文介绍了Laravel-联合+分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:

我正在尝试合并2个表recipesposts,然后将->paginate(5)添加到查询中.

I am trying to union 2 tables recipes and posts then add ->paginate(5) to the queries.

但是由于某些原因,我会收到此错误:

But for some reason I get this error:

违反基数:1222使用的SELECT语句有一个 不同的列数(SQL :(从中选择count(*)作为聚合 posts

Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from posts

代码:

$recipes = DB::table("recipes")->select("id", "title", "user_id", "description", "created_at")
                    ->where("user_id", "=", $id);

$items = DB::table("posts")->select("id", "title", "user_id", "content", "created_at")
                ->where("user_id", "=", $id)
                ->union($recipes)
                ->paginate(5)->get();

我做错什么了吗?

没有->paginate(5)的查询工作正常.

推荐答案

您是正确的,分页导致了问题.现在,您可以创建视图并查询该视图,而不是实际的表,可以手动创建Paginator:

You're right, pagination cause problem. Right now, you can create a view and query the view instead of the actual tables, or create your Paginator manually:

$page = Input::get('page', 1);
$paginate = 5;

$recipes = DB::table("recipes")->select("id", "title", "user_id", "description", "created_at")
            ->where("user_id", "=", $id);
$items = DB::table("posts")->select("id", "title", "user_id", "content", "created_at")
            ->where("user_id", "=", $id)
            ->union($recipes)
            ->get();

$slice = array_slice($items->toArray(), $paginate * ($page - 1), $paginate);
$result = Paginator::make($slice, count($items), $paginate);

return View::make('yourView',compact('result'));

这篇关于Laravel-联合+分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆