【问题标题】:Load laravel eloquent model withCount of related model使用相关模型的Count加载laravel eloquent模型
【发布时间】:2018-03-23 23:34:48
【问题描述】:

鉴于我有两个雄辩的模型:预订和客户。

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

示例输出:

  • 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。

问题

在这种情况下,预期的行为是否可能?如果是这样,我将如何急切加载预订的客户的预订总数?

【问题讨论】:

  • 你试过Booking::->with(['customer' => function($q) {$q->withCount('bookings');}])->get();吗?

标签: php laravel eloquent eager-loading


【解决方案1】:

试试这个:

public function customer() {
    return $this->belongsTo(Customer::class)->withCount('bookings');
}

Booking::whereNotCancelled()->with('customer')->get();

【讨论】:

  • 谢谢!这么简单的解决方案。这工作得很好——而且很漂亮。
猜你喜欢
  • 2017-02-04
  • 2013-06-10
  • 2014-11-25
  • 2013-12-27
  • 1970-01-01
  • 2013-05-25
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多