在laravel 5.4中使用mergeBinding()之后的where(),orderBy()

时间:2017-08-16 13:36:54

标签: laravel-5.4

你能教一下在L5.3中创建查询构建器的正确方法吗? 我有一个像这样的代码

$ query1 $ query2 都使用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中工作。 当我试图在mergeBinding之后删除 where() orderBy()时,我正在获取记录。

也许有正确的方法可以做到这一点?

请注意,在将其添加到union之前,我不希望将where()放入任何变量中。我想将我的查询作为一个阅读。

1 个答案:

答案 0 :(得分:0)

与Laravel 5.3相同但在合并绑定之前添加了where子句:

$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);

由于您在合并绑定之前使用db raw,因此请在合并绑定方法之前写入where条件。为我工作:

$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();