【问题标题】:Querying Many to Many polymorphic relationship in laravel在 laravel 中查询多对多多态关系
【发布时间】:2019-02-07 01:47:40
【问题描述】:

我有以下表格:

  • 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)

这里addressables 与contacts 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)

提前谢谢你!

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    根据Laravel's Documentation的多对多多态关系, 您必须编辑地址模型并为events 和contacts 添加方法,如下所示:

    //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) {
        //
    }
    

    【讨论】:

    • 如果不在Address 模型中定义函数,如何实现相同的目标?我想要实现的是获取所有地址及其可寻址对象和一些基于可寻址对象的过滤器
    • 如果您想过滤与特定联系人或事件匹配的地址怎么办?我找到了 whereHasMorph 但它似乎只适用于一对多,我的多对多关系我正在调用未定义的可寻址方法(我的实际上是可用的)。基本上,我希望能够将用户过滤器应用于任务查询构建器,或者在本示例中,将联系人或事件过滤器应用于地址查询构建器。
    猜你喜欢
    • 2020-12-15
    • 2018-11-02
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2019-01-04
    • 2017-02-28
    • 2013-03-05
    相关资源
    最近更新 更多