繁体   English   中英

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

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

我知道sql AND可以通过连续的where子句实现。 和OR与where(condition,'OR')。 我想从消息表中选择所有消息,其中sendTo = editor_id和sendFrom = currentUser_id或其中sendTo = currentUser_id和sendFrom = editor_id。 我有这个查询,我试图通过它来获得结果,

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

我怎样才能做到这一点? 请指教。

我有点困惑,因为您没有提供括号来知道所需的运算符优先级。

假设您想在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();

无需使用闭包。

尝试这个

$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