Reputation: 593
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.
Upvotes: 1
Views: 16187
Reputation: 4755
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.
Upvotes: 6
Reputation: 2774
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();
Upvotes: 0