2017-08-16 65 views
0

你能教什麼是L5.3 創建查詢生成器的正確方法我有一個代碼,像這樣使用其中(),排序依據()mergeBinding()在laravel後5.4

$ query1 and $ query2 is both using DB :: raw();

$res = $query1->union($query2); $querySql = $res->toSql(); $all_content_query = DB::table(DB::raw("($querySql) as a"))->mergeBindings($res)->whereIn('id', [1,2,3])->orderBy('id', 'DESC')->get()

這組代碼laravel 4.2工作,但現在沒有laravel 5.4工作。 當我試圖刪除哪裏()orderBy() mergeBinding後我越來越記錄。

也許有一個正確的方法來做到這一點?

請注意,我不希望在添加到聯合之前將where()放入任何變量中。我希望我的查詢能夠被閱讀爲一個。

回答

0
//Same issue with l 5.3 but added the where clause before merge binding 
$memo = DB::table('communications')->select('subject,sender,recipients,cc,bcc,approval_list,communications.created_at,communications.type as message_type,communications.reftag,users.name as sender_name,users.photo,users.core_role as sender_role,users.reftag as sender_tag')->join('users','users.id','=','communications.sender') 
    ->where('communications.type',1)->orderBy('created_at','desc')->limit(1); 

$queries = DB::table('communications')->select('subject,sender,recipients,cc,bcc,approval_list,communications.created_at,communications.type as message_type,communications.reftag,users.name as sender_name,users.photo,users.core_role as sender_role,users.reftag as sender_tag')->join('users','users.id','=','communications.sender') 
    ->where('communications.type',2)->orderBy('created_at','desc')->limit(1); 

$circular = DB::table('communications')->select('subject,sender,recipients,cc,bcc,approval_list,communications.created_at,communications.type as message_type,communications.reftag,users.name as sender_name,users.photo,users.core_role as sender_role,users.reftag as sender_tag')->join('users','users.id','=','communications.sender') 
    ->where('communications.type',3)->orderBy('created_at','desc')->limit(1); 

$sql = $memo->union($queries)->union($circular); 
//since you are using db raw before merge bindings, write your where conditions there before the merge binding method. worked for me 

$messages = DB::table('communications')->select('*')->from(DB::raw("(".$sql->toSql().") as messages where (sender = ".$currentUser." or find_in_set(".$currentUser.", recipients) or find_in_set(".$currentUser.", cc) or find_in_set(".$currentUser.", bcc) or find_in_set(".$currentUser.", approval_list)) "))->mergeBindings($sql->getQuery())->orderBy('created_at','desc')->get();