gpt4 book ai didi

php - 使用相关模型的Count加载laravel eloquent模型

转载 作者:行者123 更新时间:2023-12-04 01:36:32 24 4
gpt4 key购买 nike

鉴于我有两个 Eloquent 模型:预订和客户。

当我与相应客户一起列出所有预订时,我还想显示相应客户的总预订量(此预订的计数 + 所有其他预订)。

示例输出:

  • Booking1:客户 A(总共有 20 个预订)
  • Booking2:客户 B(总共有 10 个预订)
  • Booking3:客户 C(VIP:总共有 100 个预订)

为了避免 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)。

但是:这不起作用。我猜,这是因为一个 Booking 属于一个客户,而一个客户有许多 Bookings。

这是 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();

关于php - 使用相关模型的Count加载laravel eloquent模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com