简体   繁体   中英

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:

"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()

This is the results for course 2 which has not any Helps:

"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 . 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 .

I also removed array syntax from where to keep it cleaner.

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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