簡體   English   中英

Laravel如何排序合並集合

[英]Laravel how sort merge collections

我有3個查詢,我的問題是我希望合並的集合按created_at排序。

如何合並和排序三個查詢構建器集合?

        $posts1 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('pratics', 'posts.pratic_id','=','pratics.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('pratics.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

        $posts2 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('journals', 'posts.pratic_id','=','journals.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('journals.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();


        $posts3 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('exos', 'posts.exo_id','=','exos.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('exos.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

$posts = array_merge($posts1,$posts2, $posts3)->sortby('created_at');

我同意@Vitalii Strimbanu的觀點,這可能不是獲取所有記錄的最佳方法。

話雖這么說,要具體回答您的問題,我相信您唯一缺少的就是在對它調用sortby之前將合並后的數組放入集合中

$posts = collect(array_merge($posts1,$posts2, $posts3))->sortby('created_at');

希望這可以幫助!

如果要合並集合,請使用merge()函數,如下所示:

$posts1->merge($posts2)->merge($posts3)->sortby('created_at');

並且array_merge()在這里不可行。 如果要使用array_merge() ,則必須在此之前使用toArray()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM