0

Is it possible to count inside load

I have situation like this:

$offer->load([ 'coupons', 'coupons.couponItems' => function ($query) { $query->select('id', 'name'); }, 'coupons.userCoupons' => function ($query) { $query->select('id', 'coupon_id'); }, ]); 

I want to count userCoupons

If not, what is the best solution? Thank you

1 Answer 1

1

You can try adding a ->loadCount() after your load call. Unfortunately, Laravel doesn't support dot notation at that point due to complexity, so ->loadCount('coupons.userCoupons') will not work.

You can add a HasManyThrough relationship on your Offer model, however, for instance

 public function UserCoupons(): HasManyThrough { return $this->hasManyThrough(UserCoupon::class, Coupon::class); } 

You can then just do a $offer->loadCount('UserCoupons').

Sign up to request clarification or add additional context in comments.

Comments