我知道sql AND可以通过连续where子句来实现。and OR with where(condition,'OR')。我想从消息表中选择所有消息,其中sentTo = editor_id和sentFrom= currentUser_id或其中sentTo = currentUser_id和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();
我该怎么做?请建议。
我有点困惑,因为你没有提供括号来知道你想要哪个操作符优先级
假设你想要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();