Laravel雄辩的SQL查询与OR和AND与where子句 [英] Laravel eloquent SQL query with OR and AND with where clause
问题描述
我知道sql AND可以通过连续的where子句实现.和OR与where(condition,'OR'). 我想从消息表中选择所有消息,其中sendTo = editor_id和sendFrom = currentUser_id或sendTo = currentUser_id和sendFrom = editor_id. 我有这个查询,我试图通过它来获取结果,
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();
我该怎么做?请指教.
推荐答案
由于您没有提供括号来了解所需的运算符优先级,我有点困惑.
I'm a bit confuse as you didn't provide parentheses to know which operator precedence you want.
假设您要WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId)
,那么最新版本的Laravel允许您执行以下操作:
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();
无需使用闭包.
这篇关于Laravel雄辩的SQL查询与OR和AND与where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!