[英]How to join 3 tables with Laravel's Eloquent relationships with Eager Loading?
因此, order
具有一個foreign_key offer_id
。
offer
有一個Foreign_key item_id
。
一個項目可能在多個優惠中。 但是每個報價都有一個項目。
要約可能有多個訂單。 但是每個訂單都有一個報價。
當我這樣做時:
$orders = Auth::user()->orders()
->with('offer')
->get();
我得到這個:
id: 3,
user_id: 1,
offer_id: 5,
created_at: "2019-02-15 00:40:31",
updated_at: "2019-02-15 00:40:31",
offer: {
id: 5,
item_id: 3,
created_at: "2019-02-15 00:39:40",
updated_at: "2019-02-15 00:39:40"
}
如您所見,我可以為此要約獲得item_id: 3
但我想得到整個物品。 它的所有列,而不僅僅是ID。
通常,您將連接這兩個表。 如何用Eloquent做到這一點?
這是我雄辯的關系:
訂購
public function offer()
{
return $this->belongsTo(Offer::class);
}
提供
public function orders()
{
return $this->hasMany(Order::class);
}
public function item()
{
return $this->hasOne(Item::class);
}
項目
public function offers()
{
return $this->belongsToMany(Offer::class);
}
如果按食物來表示訂單中的項目,那么:
$orders = Auth::user()->orders()
->with('offer', 'offer.orders', 'offer.item')
->get();
在此之下,您會發現嵌套的渴望加載:
為了渴望加載嵌套關系,可以使用“點”語法。 例如,讓我們急切地在一項雄辯的陳述中加載本書的所有作者和所有作者的個人聯系人:
$books = App\\Book::with('author.contacts')->get();
在您的情況下,我們可以使用關系之間的點符號來嵌套它們。
$orders = Auth::user()->orders()
->with(['offer', 'offer.item'])
->get();
@MihirBhende和@swonder的答案都以正確的方式指出。
確實應該是:
$orders = Auth::user()->orders()
->with('venue')
->with('offer.item')
->get();
或(同一件事):
$orders = Auth::user()->orders()
->with(['venue', 'offer.food'])
->get();
但是Offer
和Item
模型的關系應該顛倒:
提供
public function item()
{
return $this->belongsTo(Item::class);
}
項目
public function offers()
{
return $this->hasMany(Offer::class);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.