在Laravel中查询多对多态关系

时间:2018-09-01 06:15:32

标签: php laravel-5

我有以下表格:

  • contacts(id, name, email, phone_no)
  • events(id, title, start_date, end_date)
  • addresses(id, city, state, country, zip_code)
  • addressables(id, address_id, addressable_id, addressable_type)

这里addressablescontacts events具有多对多态关系。 addressables还可以容纳其他多态模型类。

地址模型

public function addressable()
{
    return $this->morphTo();
}

事件/联系人模型

public function addresses()
{
    return $this->morphToMany(Address::class, 'addressable');
}

我想获取地址及其关联的模型。如果有人可以帮助我,我将不胜感激

  • 列出关联模型的地址
  • 列出特定型号的地址
  • 按型号类型列出地址分组

已更新

预期结果:

地址

id   |    address   
1    |    New York, USA
2    |    California, USA
3    |    Nevada, USA

联系人

id   |    name   
1    |    Albert King
2    |    Michelle Johnson
3    |    Sujit Baniya

事件

id   |    title   
1    |    Event 1
2    |    Event 2
3    |    Event 3

可寻址对象

id   |    address_id    |    addressable_id    | addressable_type   
1    |    1             |    1                 | Contact
2    |    2             |    1                 | Event
3    |    3             |    2                 | Contact

Address :: with('addressables')的结果

Address - ID 1
----Details (New York, USA)
----Contact (Albert King)
Address - ID 2
----Details (California, USA)
----Event (Event 1)
Address - ID 3
----Details (Nevada, USA)
----Contact (Michelle Johnson)

提前谢谢!

1 个答案:

答案 0 :(得分:0)

根据Laravel's Documentation的多对多态关系, 您必须像这样编辑地址模型并为eventscontacts添加方法:

//Get all the contacts that are assigned this address
public function contacts()
{
    return $this->morphedByMany('App\Contact', 'addressable');
}

//Get all the events that are assigned this address
public function events()
{
    return $this->morphedByMany('App\Event', 'addressable');
}

回答您的问题

然后要获取联系人的所有地址,您可以使用addresses动态属性,如下所示:

$contact = App\Contact::find(1);

foreach ($contact->addresses as $address) {
    //
}

对于事件:

$event = App\Events::find(1);

foreach ($event->addresses as $address) {
    //
}

最后,您可以检索地址事件和联系人,如下所示:

$address = App\Address::find(1);

foreach ($address->events as $event) {
    //
}

foreach ($address->contacts as $contact) {
    //
}