简介:
我试图合并两个表recipes
和posts
,然后将->paginate(5)
添加到查询中。
但出于某种原因,我得到了这个错误:
基数冲突: 1222使用的SELECT语句有不同数量的列(SQL:(从
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)
,查询就能正常工作。
发布于 2014-08-16 09:26:19
你说得对,分页会引起问题。现在,您可以创建一个视图并查询视图,而不是实际的表,或手动创建Paginator
:
$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'));
发布于 2016-10-26 01:42:48
我已经面临这样的问题了。我发现了一个帖子,它不是关于pagination
的,而是关于unions
的。
请参阅以下链接:用Laravel 4.1对UNION查询进行排序
@Mohamed分享了一个很好的技巧,它在我的问题上奏效了。
$query = $query1->union($query2);
$querySql = $query->toSql();
$query = DB::table(DB::raw("($querySql order by foo desc) as a"))->mergeBindings($query);
这将创建如下所示的sql:
select * from (
(select a as foo from foo)
union
(select b as foo from bar)
) as a order by foo desc;
您可以像往常一样使用Laravel的paginate
,就像$query->paginate(5)
一样。(但为了适应你的问题,你得把它分给它一点)
https://stackoverflow.com/questions/25338456
复制相似问题