简体   繁体   中英

Laravel Eloquent: filtering model by relation table

I have places and locations tables. Place could have many locations. Location belongs to Place.

Place: id title

Location: id place_id floor lat lon

class Location extends Model {

    public function place()
    {
        return $this->belongsTo('App\Place');
    }

}

And

class Place extends Model {

    public function locations()
    {
        return $this->hasMany('App\Location');
    }

}

And i need to find places, that belongs only to 1st floor. select * from places inner join locations on places.id = locations.place_id where locations.floor = 1

How does it should be done in Eloquent?

Is something similar to Place::where('locations.floor', '=', 1)->get() exists?

Yes, i know there is whereHas :

Place::whereHas('locations', function($q)
{
    $q->where('floor', '=', 1);
})->get()

but it generates a bit complex query with counts:

select * from `places` where (select count(*) from `locations` where `locations`.`place_id` = `places`.`id` and `floor` = '1') >= 1

does not this works?

class Location extends Model {

    public function place()
    {
        return $this->belongsTo('App\Place');
    }

}

$locations = Location::where('floor', '=', 1);
$locations->load('place'); //lazy eager loading to reduce queries number
$locations->each(function($location){ 
    $place = $location->place
    //this will run for each found location 
});    

finally, any orm is not for database usage optimization, and it is not worth to expect nice sql's produced by it.

I haven't tried this, but you have eager loading and you can have a condition:

$places = Place::with(['locations' => function($query)
{
    $query->where('floor', '=', 1);

}])->get();

Source

Try this :

Place::join('locations', 'places.id', '=', 'locations.place_id')
->where('locations.floor', 1)
->select('places.*')
->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM