2016-04-25 47 views
0

這似乎很簡單,但我似乎無法弄清楚。一對多/反比關係 - Laravel

我有以下型號

- >的hasMany位置

位置 - >的hasMany餐廳

餐館 - >屬於關聯位置

這意味着餐廳是基於位置通過位置

現在我想在一個特定的找到餐廳提供但不僅限於那個位置城市

提供的值爲城市名稱和位置名稱。 這樣我就可以得到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$citylocation的一部分。

我該如何做到這一點?

回答

0

可以定義這樣的HasManyThrough關係 -

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'); 
    } 
} 

退房的文檔here

+0

我的查詢將如何顯示? 假設'餐廳'屬於'城市'這將是我會用的查詢; '$ restaurants = Restaurant :: with('restaurantClass') - > where('city_id',$ city_id) - > get();' –

+0

如果您想獲得城市中的所有餐館,您需要編寫這是一個範圍。您可以訪問餐館所屬的城市 - > $ restaurant-> city; – atefth

+0

我不明白你的意思 –