[英]Querying Many to Many polymorphic relationship in laravel
我有以下表格:
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
addressables
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)
先感謝您!
根據Laravel的有關許多多態關系的文檔 ,您必須編輯地址模型並添加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) {
//
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.