1

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.

Priyanka
  • 553
  • 2
  • 6
  • 13

2 Answers2

6

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.

Javi Stolz
  • 4,720
  • 1
  • 30
  • 27
0

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();
Issam Zoli
  • 2,724
  • 1
  • 21
  • 35
  • Thanks for the efforts, but I am getting currentUser object from _construct() function in the controller. So It is available everywhere. However, your solution won't work as you are passing an object as an id. Also, if the currentUser->id was not in scope I would have got an undefined error, which I am not getting. All I get in the result is Null. Thanks – Priyanka Jul 02 '14 at 19:36
  • I think the problem is caused by $this make sure that you have the $this->data['currentUser']->id before doing the request. – Issam Zoli Jul 02 '14 at 19:38
  • I got it worked,`$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();` Thanks for your efforts @Issam – Priyanka Jul 02 '14 at 19:43