我有3张桌子
酒店与城市有关,而城市与省有关。 城市ID将保存在酒店表的城市字段中。 如何在“酒店”模型中访问城市名称和省名?
在酒店模型中,我这样写:
public function city(){
return $this->belongsTo(City::class);
}
在城市模型中,我有这个:
public function hotel(){
return $this->hasMany(Hotel::class);
}
public function province(){
return $this->belongsTo(Province::class);
}
和省份
public function cities(){
return $this->hasMany(City::class);
}
答案 0 :(得分:0)
Has Many Through关系就是您要寻找的。 p>
答案 1 :(得分:0)
public function provinces()
{
return $this->hasManyThrough('App\Province', 'App\City');
}
在酒店模型中,您可以通过使用控制器来访问省名,例如
$hotel = Hotel::find(1);
dd($hotel->provinces);
并在刀片中使用该变量