Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eloquent filter result based on foreign table attribute

I'm using laravel and eloquent.
Actually I have problems filtering results from a table based on conditions on another table's attributes.
I have 3 tables:

  • venue
  • city


    here are the relationships:
    a city has many locations and a location belongs to a city.
    a location belongs to a venue and a venue has one location.

I have a city_id attribute on locations table, which you may figured out from relationships.

The question is simple:
how can I get those venues which belong to a specific city?
the eloquent query I expect looks like this:
$venues=Venue::with('location')->where('location.city_id',$city->getKey());

Of course that's not gonna work, but seems like this is common task and there would be an eloquent command for it.
Thanks!

like image 272
Mehrdad Shokri Avatar asked Sep 02 '15 18:09

Mehrdad Shokri


1 Answers

A couple of options:

$venues = Venue::whereIn('location_id', Location::whereCityId($city->id)->get->lists('id'))
    ->get();

Or possibly using whereHas:

$venues = Venue::whereHas('location', function($query) use ($city) {
    $query->whereCityId($city->id);
})->get();
like image 103
EricMakesStuff Avatar answered Sep 30 '22 17:09

EricMakesStuff