PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] Laravel Eloquent match to all parameters of join

 January 22, 2022     eloquent, laravel, laravel-7     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing