Php 加载带有相关模型计数的laravel雄辩模型
鉴于此,我有两个雄辩的模型:预订模型和客户模型 当我列出各个客户的所有预订时,我还想显示各个客户的总预订量(此预订数+所有其他预订数) 示例输出:Php 加载带有相关模型计数的laravel雄辩模型,php,laravel,eloquent,eager-loading,Php,Laravel,Eloquent,Eager Loading,鉴于此,我有两个雄辩的模型:预订模型和客户模型 当我列出各个客户的所有预订时,我还想显示各个客户的总预订量(此预订数+所有其他预订数) 示例输出: 预订1:客户A(总共有20个预订) 预订2:客户B(共有10个预订) 预订3:客户C(VIP:总共有100次预订) 为了避免n+1问题(显示此项时每个预订一个附加查询),我希望为客户加载bookingsCount 这些关系是: 预订:public function customer(){return$this->belongsTo(custome
- 预订1:客户A(总共有20个预订)
- 预订2:客户B(共有10个预订)
- 预订3:客户C(VIP:总共有100次预订)
bookingsCount
这些关系是:
预订:public function customer(){return$this->belongsTo(customer::class)}
客户:public function bookings(){return$this->hasMany(Booking::class)}
查询急加载预订的示例
public function customerBookings()
{
// return the bookings of this booking's customer
return $this->hasManyThrough(Booking::class, Customer::class);
}
正在工作,但不急于加载BookingCount:
Booking::whereNotCancelled()->with('customer')->get();
不工作:
Booking::whereNotCancelled()->with('customer')->withCount('customer.bookings')->get();
我了解到,您不能在相关模型的字段上使用with count
,但您可以通过关系创建hasManyThrough
并在该关系上调用with count
,例如Booking::whereNotCancelled()->with count('customerBookings')代码>()
但是:这不起作用。我猜,这是因为一个预订属于一个客户,而一个客户有很多预订
以下是课堂预订的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\u id
问题
在这种情况下,预期的行为可能吗?如果是这样,我将如何加载预订客户的总预订数量?尝试以下方法:
public function customer() {
return $this->belongsTo(Customer::class)->withCount('bookings');
}
Booking::whereNotCancelled()->with('customer')->get();
您是否尝试过使用(['customer'=>function($q){$q->withCount('bookings');}])->get()进行Booking::->代码>?谢谢!这是一个简单的解决方案。这非常好用——而且很漂亮。