Saturday, January 22, 2022

[FIXED] Laravel Eloquent match to all parameters of join

Issue

I have a table that houses hotel ids and amenity ids. When a user chooses amenities i need to only pull hotels that have ALL of the chosen amenities. As of now it gets me all hotels that have at least one. How can i change this builder query to handle it so it does not include hotels that do not have all of them.

$builder = Hotels::query(); 
$builder->select('hotels.id','hotels'.'hotels_name')
$request_amenities = $request->amenities;
$builder->join('amenities_hotels', function ($join) use($request_amenities) {
    $join->on('amenities_hotels.hotel_id', '=', 'hotel.id')
            ->whereIn('amenities_hotels.amenities_id', $request_amenities);
});

Solution

It's something like WhereAll you need ...

you have to add whereHas, for every Item in your array.

 $builder = Hotels::query();
        $builder->select('hotels.id', 'hotels' . 'hotels_name');
        $request_amenities = $request->amenities;
        if($request_amenities!=null)
        {
            for ($i = 0; $i < $this->count($request_amenities); $i++) {
                $builder = $builder->whereHas('amenitiesHotels', function ($query) use ($i, $request_amenities) {
                    $query->where('amenities_hotels.amenities_id', $request_amenities[$i]);
                });
        }

see more about where in all in this question



Answered By - OMR

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.