Ad

Laravel Eloquent Relationships On 3 Tables

- 1 answer

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.

enter image description here

Ad

Answer

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, e.g.:

@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

Ad
source: stackoverflow.com
Ad