简体   繁体   中英

Laravel eloquent relation with 4 tables

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?

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM