Search code examples
mysqllaraveleloquentmany-to-manyeloquent-relationship

Eloquent - Return Registry only if it doesn't have a value asossiated in the relationship


I have this question, maybe someone can help me :)

Student::whereHas('courses.group', function ($query) use ($year) {
            $query->where('year', '!=', $year);
        })->orDoesntHave('courses')->where('active', '=', '1')->get()

I have this query in eloquent, it works, but I have a problem. What I really need to get on that query is all the registries students that have groups associated through the pivot courses, in which of all the groups it has, it should return the student only if it doesn´t have a $year value registered in his groups, or if doesn't have any courses. Any idea? :)


Solution

  • WhereHas() has the inverse logic with whereDoesntHave(). You need to change the query logic but should be straight forward, as i understand it this should work.

    Student::whereDoesntHave('courses.group', function ($query) use ($year) {
        $query->where('year', $year);
    })->orDoesntHave('courses')
    ->where('active', '=', '1')
    ->get();