samedi 21 juillet 2018

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire