如何在 'where' 子句中的 laravel 查询构建器中使用方括号?

How to use brackets in laravel query builder in 'where' clause?

我是 laravel 的新人,我在使用它的查询生成器时遇到了问题。我正在 运行 宁此代码

return DB::table('t_chat')
    ->where('chat_msg_from', '=', auth()->user()->id)
    ->where('chat_msg_to', '=', $to_id)
    ->orWhere('chat_msg_from', '=', $to_id)
    ->where('chat_msg_to', '=', auth()->user()->id)
    ->get();

此代码将 运行 查询如下:

SELECT * FROM t_chat WHERE chat_msg_to = 2 AND chat_msg_from = 1 
OR
chat_msg_to = 1 AND chat_msg_from = 2

但我想要它:

SELECT * FROM t_chat WHERE (chat_msg_to = 2 AND chat_msg_from = 1) 
OR
(chat_msg_to = 1 AND chat_msg_from = 2)

这样你可以在查询中添加条件:

return DB::table('t_chat')
->where('chat_msg_from', '=', auth()->user()->id)
->where('chat_msg_to', '=', $to_id)
->orWhere(function($q) {
     $q->where('chat_msg_from', '=', $to_id)
       ->Where('chat_msg_to', '=', auth()->user()->id);
     })
->get();

捕获:

DB::table('t_chat')
    ->where(function ($query) {
        $query->where('chat_mgs_to', '=', 2)
        ->Where('chat_mgs_from', '=', 1);
    })
    ->orWhere(function ($query) {
        $query->where('chat_mgs_to', '=', 1)
        ->Where('chat_mgs_from', '=', 2);
    })
    ->get();

您可以在 laravel 查询中使用 whereRaw

return DB::table('t_chat')->whereRaw("(chat_msg_from=auth()->user()->id 
   and chat_msg_to=$to_id) or (chat_msg_from=$to_id and chat_msg_to =
    auth()->user()->id)")->get();