Laravel - 同时联合 + 分页?
简介:
我正在尝试合并 2 个表 recipes
和 posts
,然后将 ->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:(选择计数(*)作为聚合来自帖子
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)
查询工作正常.
Without ->paginate(5)
the query works fine.
推荐答案
你说得对,分页导致问题.现在,您可以创建一个视图并查询该视图而不是实际的表,或手动创建您的 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'));
相关文章