简体   繁体   English

Laravel雄辩或关系何处

[英]Laravel Eloquent orWhere on relationships

I've a Course model which has many Help model. 我有一个课程模型,其中包含许多帮助模型。

public function helps() {
    return $this->hasMany(Help::class);
}

Now the problem is when i try to get helps of a specific course with where and orwhere I have a little problem. 现在的问题是,当我尝试在某个地方或某个地方遇到一些小问题时寻求特定课程的帮助时。

$helps = $course->helps()
    ->where(['from_id' => 497])->orWhere(['to_id' => 497])->get();

The result is correct when I try to get helps of course 1: 当我尝试获得课程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,
        }
    ]

But when I try to get helps of any course that has not helps, instead of empty array it returns the orWhere fields with neglecting the $course->helps() 但是,当我尝试从没有帮助的任何课程中获得帮助时,它会返回orWhere字段,而忽略了$course->helps() orWhere $course->helps()而不是空数组

This is the results for course 2 which has not any 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,
        }
    ]

The problem is orWhere . 问题是或在orWhere To generate correct query you should wrap condition into additional closure. 为了生成正确的查询,您应该将条件包装到其他闭包中。

$helps = $course->helps()->where(function($q) {
    $q->where('from_id', 497)->orWhere('to_id', 497)
})->get();

Wrapping with closure adds ( ) in desired place. 用闭包包装在所需位置添加()。

Now you will have condition where A AND (B OR C) and before you had A AND B OR C what really means (A AND B) OR C . 现在,您将具有A AND (B OR C)条件,并且在获得A AND B OR C ,实际上意味着(A AND B) OR C

I also removed array syntax from where to keep it cleaner. 我还从保持干净的where删除了数组语法。

尝试这个:

$helps = $course->helps->where('from_id', 497)->orWhere('to_id', 497);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM