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

farshadf's avatar

query the relationship and get result according to relation query

hi i want to do a query to get relations of a model and sort the parent model by the query which was done in my relation so like below :

  $data = Accommodation::with([  'accommodationRoomsLimited.discount', 'accommodationRoomsLimited', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
            $query->whereDate('from_date', '<=', $from_date);
            $query->whereDate('to_date', '>=', $to_date);
        }])->when($bed_count, function ($q, $bed_count) {
            $q->with([
                'accommodationRoomsLimited' => function ($q) use ($bed_count) {
                    $q->where('bed_count', $bed_count);
                }
            ]);

so when user send bed_count 3 for i this query only shows rooms that have bed_count of 3 and if they dont it shows the accommodation but with empty rooms object as relation . i want my result this way that if the room doesnt have the bed_count of 3 the accommodation it self wont show in result . how can i achive that ?? thanks .

0 likes
0 replies

Please or to participate in this conversation.