我有3個查詢,我的問題是我想合併收集排序created_at
。Laravel如何排序合併收集
如何合併和排序三個查詢構建器集合?
$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');
我建議你'UNION'所有的查詢,而不是在php中合併這3個數組。 https://laravel.com/docs/5.3/queries#unions –
這樣的聯合:$ posts1 = \ DB :: table('posts') - > select('posts。*','users.nom', 'pratics.titre') - > join('pratics','posts.pratic_id','=','pratics.id') - > join('users','posts.user_id','=',' users.id ') - >在哪裏(' pratics.user_id」,$ id)的; $ 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) - >工會($ posts1) - >獲得(); – nabil