一对多/反向关系 - Laravel

时间:2016-04-25 08:40:03

标签: laravel laravel-5 eloquent

这看起来很简单,但我似乎无法弄明白。

我有以下型号

城市 - > HasMany 地点

地点 - > HasMany 餐厅

餐厅 - > BelongsTo 地点

这意味着餐厅通过地点

链接到城市

现在我想根据提供的位置在特定城市中找到餐馆,但不仅限于该位置,而是城市

提供的值包括城市名称和位置名称。 所以我可以获得city_idlocation_id

// this will get a city with all locations
$city = City::with('locations')->where('value', $c)->first();
$city_id = $city->id;

// this will get the location id
$location = Location::where('value', $l)->first();
$location_id = $location->id;

因此,我的$restaurants查询应找到location属于location $city的所有餐馆。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

You can define a HasManyThrough relationship like this -

class City extends Model
{
    public function locations()
    {
        return $this->hasMany('App\Location');
    }
    public function restaurants()
    {
        return $this->hasManyThrough('App\Restaurant', 'App\Location');
    }
}

class Location extends Model
{
    public function City()
    {
        return $this->belongsTo('App\City');
    }
    public function restaurants()
    {
        return $this->hasMany('App\Restaurant');
    }
}
class Restaurant extends Model
{
    public function location()
    {
        return $this->belongsTo('App\Location');
    }
    public function city()
    {
        return $this->belongsTo('App\City');
    }
}

Check out the docs here.