简体   繁体   English

Laravel雄辩的SQL查询与OR和AND与where子句

[英]Laravel eloquent SQL query with OR and AND with where clause

I know that sql AND can be achieved by consecutive where clauses. 我知道sql AND可以通过连续的where子句实现。 and OR with where(condition,'OR'). 和OR与where(condition,'OR')。 I want to choose all the messages from message table where sentTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = editor_id. 我想从消息表中选择所有消息,其中sendTo = editor_id和sendFrom = currentUser_id或其中sendTo = currentUser_id和sendFrom = editor_id。 I have this query which I am trying to get the result through, 我有这个查询,我试图通过它来获得结果,

    $this->data['messages'] = Message::where(function ($query) use($uId) {
        $query->where('sentTo', '=', $this->data['currentUser']->id)
            ->orWhere('sentFrom', '=', $uId);
            })
    ->where(function ($query) use($uId){
             $query->where('sentTo', '=', $uId)
                     ->orWhere('sentFrom', '=', $this->data['currentUser']->id);
            })
    ->get();

How can I do this? 我怎样才能做到这一点? Please advice. 请指教。

I'm a bit confuse as you didn't provide parentheses to know which operator precedence you want. 我有点困惑,因为您没有提供括号来知道所需的运算符优先级。

Assuming you want WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId) then latest version of Laravel allows you to do: 假设您想在WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId)那么最新版本的Laravel允许您执行以下操作:

    Message::where(['editor_id' => $editorId, 'sentFrom' => $currentUserId])
    ->orWhere(['sentTo' => $currentUserId, 'sentFrom' => $editorId])->get();

No need to use closures. 无需使用闭包。

Try this 尝试这个

$this->data['messages'] = Message::where(function ($query) use($uId) {
    $query->where('sentTo', '=', $this->data['currentUser']->id)
          ->where('sentFrom', '=', $uId);
})-> orWhere(function ($query) use($uId){
    $query->where('sentTo', '=', $uId)
          ->Where('sentFrom', '=', $this->data['currentUser']->id);
})->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM