Laravel雄辩的关系,在3张桌子上 [英] Laravel Eloquent Relationships on 3 tables

查看:53
本文介绍了Laravel雄辩的关系,在3张桌子上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问我有3个表要显示,但是其中3个表是相关的.

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

第一个表是GROUPS,第二个表是CONTACTS,最后一个表是PHONE_NUMBERS.

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

我正在使用Laravel Framework.问题是,我不知道要使用什么雄辩的关系,我想显示GROUPS表的内容,而CONTACTS将显示在GROUPS下,而PHONE NUMBERS将显示在CONTACTS.

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();

这将为您提供一组组.每个组的 contacts 属性中将包含一组联系人.每个联系人的 phoneNumbers 属性中都将包含电话号码集合.通过遍历这些集合,您应该能够获得呈现所需结构所需的数据,例如:

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

有关如何使用Eloquent建模数据的所有必要信息,可以在文档中找到: https://laravel.com/docs/master/eloquent

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

这篇关于Laravel雄辩的关系,在3张桌子上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆