鉴于我有两个雄辩的模型:预订和客户。
当我列出所有预订以及相应的客户时,我还想显示相应客户的总预订金额(此预订的数量+所有其他预订)。
示例输出:
为了避免n + 1问题(在显示此问题时每次预订另外一个查询),我希望急切地为客户加载bookingsCount
。
关系是:
预订:public function customer() { return $this->belongsTo(Customer::class) }
客户:public function bookings() { return $this->hasMany(Booking::class) }
以预先加载方式查询预订的示例
工作,但没有急切加载bookingsCount:
Booking::whereNotCancelled()->with('customer')->get();
不工作:
Booking::whereNotCancelled()->with('customer')->withCount('customer.bookings')->get();
我了解到,您无法在相关模型的字段上使用withCount
,但您可以创建hasManyThrough
关系并在该关系上调用withCount
,例如Booking::whereNotCancelled()->withCount('customerBookings');
(see accepted answer here)。
但是:这不起作用。我想,这是因为预订属于客户而客户有很多预订。
以下是预订类型的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
。
问题
在这种情况下,预期的行为是否可行?如果是这样,我将如何急切加载预订客户的预订总数?
答案 0 :(得分:3)
试试这个:
public function customer() {
return $this->belongsTo(Customer::class)->withCount('bookings');
}
Booking::whereNotCancelled()->with('customer')->get();