Saman Sattari
Saman Sattari

Reputation: 3568

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,
        }
    ]

Upvotes: 0

Views: 3105

Answers (2)

Jinal Somaiya
Jinal Somaiya

Reputation: 1971

try this:

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

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

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.

Upvotes: 3

Related Questions