简体   繁体   中英

Laravel Eloquent Relationships on 3 tables

Please i have 3 tables that i want to display but 3 of the tables are related.

The first table is GROUPS , second is CONTACTS , and the last is PHONE_NUMBERS .

I am using Laravel Framework. The problem is, i don't know the eloquent relation to use, i want to display content of the the GROUPS table, while the CONTACTS will display under the GROUPS and the PHONE NUMBERS will display under the CONTACTS .

Please advice me on how to achieve this. Attached is an image of how it will look when finished.

在此处输入图片说明

Each group can have multiple contacts, and each contact can have multiple phone numbers, you'll need to define one-to-many relation from group to contact and from contact to phone number:

class Group extends Model {
  public function contacts() {
    return $this->hasMany(Contact::class);
  }
}

class Contact extends Model {
  public function phoneNumbers() {
    return $this->hasMany(PhoneNumber::class);
  }
}

With relations defined, you will be able to load groups, their contacts and contacts' phone numbers with:

$groups  = Group::with(['contacts', 'contacts.phoneNumbers'])->get();

This will give you a collection of groups. Each of groups will contain a collection of contacts in their contacts property. Each of contacts will contain phone numbers collection in their phoneNumbers properties. By iterating through those collections you should be able to get data needed to render the structure you need, eg:

@foreach($groups as $group)
  {{ $group->name }}
  @foreach ($group->contacts as $contact)
    {{ $contact->name }}
    @foreach ($contact->phoneNumbers as $number)
      {{ $number->number }}
    @endforeach
  @endforeach
@endforeach

All necessary information on how to model your data with Eloquent can be found in the documentation: https://laravel.com/docs/master/eloquent

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