2016-12-06 104 views
0

所以基本上,我有4張桌子。Laravel與4張桌子的雄辯關係

表1:Fylker(縣) 表2:Kommuner(市政) 表3:Poststed(郵政) 表4:Postnumre(郵編)

我目前使用Laravel 5.3和數據庫是設置和種子。 現在,我想知道的是,我應該使用4種不同的模型嗎? 每個表都與前一個關係。

我想要的是從Fylker獲得一行,然後使用一些關係來獲得與Fylke關聯的Kommuner,並與另一個關係獲取所有關聯的Poststeder和另一個關係以獲取所有Postnumre。

喜歡的東西,這是我想達到的目標:

$fylke -> kommuner -> poststeder -> postnumre; 

我將如何做到這一點?

enter image description here

enter image description here

enter image description here

enter image description here

回答

0

在Laravel這是很好的做法,模型爲每個表。您可以解決您的problev這樣的:

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

在Poststed型號:

public function postnumres() { 
    return $this->hasMany(Postnumre::class); 
} 

,你可以得到一切PostnumresFylke這樣:$fylke->postnumres