Search code examples
laravellaravel-3eloquent

Laravel3 Eloquent: Query for attribute in Many-To-Many Relation


This Problem blows my mind at the moment: I have the following relation: Groups --> Intermediate Many-To-Many Table <-- Cities (Every Group can have multiple Cities assigned)

Now I want to get all the Group-Models where the assigned City is either id X and id Y. Like Saying "get me all the groups which are assigned to Boston and New York"

Is that possible with Laravel 3's Eloquent?

Thank you very much! Matthias


Solution

  • In my experience, where clauses do not work inside of many-to-many relationships. But they do work if you eager load them.

    Group::with(array('cities' => function($q) {
        $q->or_where('id', '=', X);
        $q->or_where('id', '=', Y);
    })->get();