【问题标题】:Laravel 4 - Union + orederBy results with the wrong queryLaravel 4 - Union + orederBy 结果错误查询
【发布时间】: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

感谢您的帮助!

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案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]);
    

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多