首页 文章

Laravel 4 - Union orederBy查询结果错误

提问于
浏览
2

我尝试从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 from posts user_id ='102'order by created_at desc)union(select user,title,user_id,description,created_at from recipe where user_id ='102')

我希望获得的查询:

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

知道为什么吗?

我的laravel版本是:V4.2.8

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

谢谢您的帮助!

1 回答

  • 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]);
    

相关问题