Akshay Ashokan
Akshay Ashokan

Reputation: 17

how to write where condition in relation table in Laravel in query

I have 3 table that is Resort, Booking, Expense, these tables are join with relation. the code is given below,

$resorts = Resort::where('status',1)->with('bookings')->withSum('bookings', 'amount')
        ->with('expenses')->withSum('expenses', 'amount')->get();

I want to sort this table using the date field. how could I use the wherebetween in this query for bookings and expense?

Upvotes: 0

Views: 65

Answers (1)

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

you can pass array in with() like this

$resorts = Resort::where('status', 1)
    ->with(
        ['bookings' => function ($q) {
            $q->wherebetween('colName', ['startDate','endDate']);
        }]
    )->withSum('bookings', 'amount')
    ->with(
        ['expenses' => function ($q) {
            $q->wherebetween('colName', ['startDate','endDate']);
        }]
    )->withSum('expenses', 'amount')
    ->get();

ref link https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads

Upvotes: 1

Related Questions