Laravel 4 - Union + orederBy 结果错误查询

Posted

技术标签:

【中文标题】Laravel 4 - Union + orederBy 结果错误查询【英文标题】:Laravel 4 - Union + orederBy results with the wrong query 【发布时间】:2014-10-18 21:02:42 【问题描述】:

我尝试使用联合从 2 个表中提取数据,并通过“created_at”DESC 对它们进行排序。但由于某种原因,使用错误的查询编写 ->orderBy 结果 - 我在第一个查询中而不是在它们之外有 created_at。

代码:

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

    $items = $posts->union($recipes);
    $items = $items->orderBy("created_at", "DESC")->get();

我得到的查询:

(select id, title, user_id, content, created_at from posts where user_id = '102' order by created_at desc) union (select id, title, user_id, description, created_at from recipes where user_id = '102')

我希望得到的查询:

(select id, title, user_id, content, created_at from posts where user_id = '102') union (select id, title, user_id, description, created_at from recipes where user_id = '102') order by created_at 描述

知道为什么吗?

我的laravel版本是:V4.2.8

相关话题:https://github.com/laravel/framework/pull/3901

感谢您的帮助!

【问题讨论】:

【参考方案1】:

在控制器中

use DB;

在控制器函数内部

$items=DB::select('select id, title, user_id, content, created_at from posts where user_id =? union  select id, title, user_id, description, created_at from recipes where user_id = ? order_by created_at desc',[$id,$id]);

【讨论】:

以上是关于Laravel 4 - Union + orederBy 结果错误查询的主要内容,如果未能解决你的问题,请参考以下文章

Laravel UNION ALL 不适用于 where 语句

Laravel 5.4:无法从关系中检索数据

每次不工作期间的 Laravel 收集联合

mysql union和union all的区别

实训4:union 联合查询

实训4:union 联合查询