I have 3 tables with their models.
User.php
public function bookings() {
return $this->hasMany(Booking::class);
}
//---------------------------------------------------------
Booking.php
Columns: id, status [confirmed, pending], user_id, timestamps
public function user() {
return $this->belongTo(User::class);
}
public function bookingItems() {
return $this->hasMany(BookingItem::class);
}
//------------------------------------------------------------
BookingItem.php
Columns: id, booking_id, item_type, item_num, timestamps
public function booking() {
return $this->belongTo(Booking::class);
}
A user can have many bookings and each booking has many different items.
I want to get a user's sum of item_num' column of this year but only ofconfirmed` bookings.
I can't figure out how to achieve that?
I thought I'd create a new method in Booking.php -
public function getUserBookingsCount($userId=null)
{
$userId = $userId ?? auth()->id();
$d = $this->whereHas('user', function($q) use($userId) {
$q->where('user_id', $userId);
})->withCount('bookingItems')->sum('item_num');
dd($d)
--> Not sure how to add status condition here
--> also it gives all bookings with sum as extra column instead I'd like sum of all bookings
}