Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mumarsharjeel@gmail.com's avatar

Filter model based on multiple relations

I have a model Booking which have hasMany rooms, hasMany expenses and hasMany payments. I want to get those bookings which fulfill following condition:

booking->rooms->sum('price') + booking->expenses->sum('amount') < booking->payments->sum('amount')

0 likes
1 reply
rodrigo.pedra's avatar
Level 56
$bookings = Booking::query()
    ->withSum('rooms', 'amount')
    ->withSum('expenses', 'amount')
    ->withSum('payments', 'amount')
    ->havingRaw('rooms_sum_amount + expenses_sum_amount < payments_sum_amount')
    ->withCasts([
        'rooms_sum_amount' => 'float',
        'expenses_sum_amount' => 'float',
        'payments_sum_amount' => 'float',
    ])
    ->get();
1 like

Please or to participate in this conversation.