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

Pri*_*nka 0 php mysql laravel

我知道 sql AND 可以通过连续的 where 子句来实现。和 OR 与 where(condition,'OR')。我想从消息表中选择所有消息,其中 sentTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = 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();
Run Code Online (Sandbox Code Playgroud)

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

Jav*_*olz 5

我有点困惑,因为您没有提供括号来了解您想要的运算符优先级。

假设您想要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();
Run Code Online (Sandbox Code Playgroud)

不需要使用闭包。