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

时间:2014-08-25 16:43:25

标签: php laravel laravel-4

我尝试从2个表中使用union来提取数据,并通过“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();

我得到的查询:

  

(从帖子中选择id,title,user_id,content,created_at   user_id ='102'order by created_at desc)union(select id,title,   user_id,description,created_at from recipes where user_id ='102')

我希望获得的查询:

  

(从帖子中选择id,title,user_id,content,created_at   user_id ='102')union(选择id,title,user_id,description,   来自配方的created_at,其中user_id ='102')按created_at排序   降序

知道为什么吗?

我的laravel版本是:V4.2.8

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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]);