[英]Laravel Eloquent orWhere on relationships
我有一个课程模型,其中包含许多帮助模型。
public function helps() {
return $this->hasMany(Help::class);
}
现在的问题是,当我尝试在某个地方或某个地方遇到一些小问题时寻求特定课程的帮助时。
$helps = $course->helps()
->where(['from_id' => 497])->orWhere(['to_id' => 497])->get();
当我尝试获得课程1的帮助时,结果是正确的:
"data": [
{
"id": 12,
"message": "hi there",
"from_id": 497,
"to_id": 1,
"course_id": 1,
},
{
"id": 108,
"message": "hi ...",
"from_id": 1,
"to_id": 497,
"course_id": 1,
},
{
"id": 197,
"message": "ok body",
"from_id": 1,
"to_id": 497,
"course_id": 1,
}
]
但是,当我尝试从没有帮助的任何课程中获得帮助时,它会返回orWhere
字段,而忽略了$course->helps()
orWhere
$course->helps()
而不是空数组
这是课程2的结果,没有任何帮助:
"data": [
{
"id": 108,
"message": "hi ...",
"from_id": 1,
"to_id": 497,
"course_id": 1,
},
{
"id": 197,
"message": "ok body",
"from_id": 1,
"to_id": 497,
"course_id": 1,
}
]
问题是或在orWhere
。 为了生成正确的查询,您应该将条件包装到其他闭包中。
$helps = $course->helps()->where(function($q) {
$q->where('from_id', 497)->orWhere('to_id', 497)
})->get();
用闭包包装在所需位置添加()。
现在,您将具有A AND (B OR C)
条件,并且在获得A AND B OR C
,实际上意味着(A AND B) OR C
我还从保持干净的where
删除了数组语法。
尝试这个:
$helps = $course->helps->where('from_id', 497)->orWhere('to_id', 497);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.