简体   繁体   中英

Laravel eloquent SQL query with OR and AND with where clause

I know that sql AND can be achieved by consecutive where clauses. and OR with 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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