[英]Laravel eloquent relation with 4 tables
因此,基本上,我有4张桌子。
表1:Fylker(县)表2:Kommuner(市镇)表3:Poststed(邮政)表4:Postnumre(邮编)
我目前正在使用Laravel 5.3,并且已设置数据库并设置了种子。 现在,我想知道的是,我应该为此使用4种不同的模型吗? 每个表都与上一个表有关系。
我想要的是从Fylker获取行,然后使用某种关系获取与Fylke关联的Kommuner,并使用另一种关系获取所有关联的Poststeder,并使用另一种关系获取所有Postnumre。
我想要达到的目的是这样的:
$fylke -> kommuner -> poststeder -> postnumre;
我该怎么做?
在Laravel中,为每个表建立模型是一个好习惯。 您可以这样解决您的问题:
在Fylker模型中:
public function kommuners(){
return hasMany(Kommuner::class);
}
public function poststeds(){
$kommuners = $this->kommuners;
$poststeds = array();
foreach ($kommuners as $kommuner) {
$poststeds[] = $kommuner->poststeds;
}
}
public function postnumres() {
$poststeds = $this->poststeds;
$postnumres = array();
foreach ($poststeds as $poststed) {
$postnumres[] = $poststed->postnumres;
}
}
在Kommuner模型中:
public function poststeds() {
return $this->hasMany(Poststed::class);
}
在发布模型中:
public function postnumres() {
return $this->hasMany(Postnumre::class);
}
您可以像这样从Fylke
获取所有Postnumres
: $fylke->postnumres
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.