[英]Load laravel eloquent model withCount of related model
鑒於我有兩個雄辯的模型:預訂和客戶。
當我列出所有預訂以及相應的客戶時,我還想顯示相應客戶的總預訂金額(此預訂的計數+所有其他預訂)。
示例輸出:
為了避免n + 1問題(在顯示此問題時每次預訂一次額外查詢),我想急切為客戶加載bookingsCount
。
關系是:
預訂: public function customer() { return $this->belongsTo(Customer::class) }
客戶: public function bookings() { return $this->hasMany(Booking::class) }
使用預先加載查詢預訂的示例
工作,但沒有急切加載預訂帳戶:
Booking::whereNotCancelled()->with('customer')->get();
不工作:
Booking::whereNotCancelled()->with('customer')->withCount('customer.bookings')->get();
我了解到,你不能在相關模型的字段上使用withCount
,但你可以創建一個hasManyThrough
關系並在該關系上調用withCount
,例如Booking::whereNotCancelled()->withCount('customerBookings');
( 見這里接受的答案 )。
但是:這不起作用。 我想,這是因為預訂屬於客戶而客戶有很多預訂。
這是類Booking的hasManyThrough關系
public function customerBookings()
{
// return the bookings of this booking's customer
return $this->hasManyThrough(Booking::class, Customer::class);
}
這是hasManyThrough的失敗測試
/**
* @test
*/
public function it_has_a_relationship_to_the_customers_bookings()
{
// Given we have a booking
$booking = factory(Booking::class)->create();
// And this booking's customer has other bookings
$other = factory(Booking::class,2)->create(['customer_id' => $booking->customer->id]);
// Then we expect the booking to query all bookings of the customer
$this->assertEquals(3, Booking::find($booking->id)->customerBookings()->count());
}
報告錯誤
no such column: customers.booking_id (SQL: select count(*) as aggregate from "bookings" inner join "customers" on "customers"."id" = "bookings"."customer_id" where "customers"."booking_id" = efe51792-2e9a-4ec0-ae9b-a52f33167b66)
沒有驚喜。 customer.booking_id
沒有這樣的列。
問題
在這種情況下,預期的行為是否可行? 如果是這樣,我將如何急切加載預訂客戶的預訂總數?
嘗試這個:
public function customer() {
return $this->belongsTo(Customer::class)->withCount('bookings');
}
Booking::whereNotCancelled()->with('customer')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.