Brief:

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:

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

Code:

$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();

我做错什么了吗?

Without ->paginate(5) the query works fine.

推荐答案

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相关问答推荐

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

Laravel 联合和分页

在 blade laravel 中以格式编号显示长数字

如何使用 laravel 更新单个值

我的共享主机上的每个帖子请求都出现 503 服务不可用

如何防止 Laravel 路由被直接访问(即非 ajax 请求)

Laravel:如何在 laravel 查询生成器中使用派生表/子查询

Laravel API 版本控制文件夹 struct

如何在 NetBeans 中添加带有点 (blade.php) 的自定义文件扩展名?

Laravel 中未加密的 cookie

合并和排序两个 Eloquent 集合?

在 laravel 5.2 中禁用特定路由的 Web 中间件

Laravel - 批量分配异常错误

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

Laravel:方法[显示]不存在

嘲笑没有匹配的关闭处理程序

Laravel 中的单会话登录

如何使 Laravel (Blade) 文本字段只读

Laravel 排序集合,然后按键

Laravel or where