【问题标题】:How to use brackets in laravel query builder in 'where' clause?如何在'where'子句中使用laravel查询构建器中的括号?
【发布时间】:2020-07-29 14:51:33
【问题描述】:

我是 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)

【问题讨论】:

  • 请注意,您不需要任何额外的括号。

标签: sql database laravel where-clause brackets


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    赶上:

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

    【讨论】:

      【解决方案3】:

      你可以在 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();
      

      【讨论】:

        猜你喜欢
        • 2015-06-03
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 1970-01-01
        • 2018-12-15
        • 2017-01-05
        • 2016-10-06
        • 2013-10-19
        相关资源
        最近更新 更多