Reputation: 2843
So basically, I have 4 tables.
Table 1: Fylker (Counties) Table 2: Kommuner (Municipalities) Table 3: Poststed (Postal) Table 4: Postnumre (Zip)
I'm currently using Laravel 5.3 and the databases are setup and seeded. Now, what I'm wondering about, should I use 4 different models for this? Every table has relations to the previous.
What I want is to get a row from Fylker, then use some relation to get the Kommuner associated with the Fylke, and with another relation get all associated Poststeder and another relation to get all the Postnumre.
Something like this is what I want to achieve:
$fylke -> kommuner -> poststeder -> postnumre;
How would I do this?
Upvotes: 0
Views: 122
Reputation: 785
In Laravel it's good practice to have model for every table. You may solve your problev like this:
In Fylker model:
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;
}
}
In Kommuner model:
public function poststeds() {
return $this->hasMany(Poststed::class);
}
In Poststed model:
public function postnumres() {
return $this->hasMany(Postnumre::class);
}
And you can get all Postnumres
from Fylke
like this: $fylke->postnumres
Upvotes: 0