Laravel selects only a great value from a related model (Many to Many relationship)

This is an application for booking hotels, 1 hotel can have many rooms, in one room there can be many amenities (facilities).

My models:

Room Model:

class Room extends Model
{

    public function amenities()
    {
        return $this->belongsToMany('App\Amenities')->withTimestamps();
    }

    public function hotel(){
        return $this->belongsTo('App\Hotel');
    }

}

Characteristics Model:

class Amenities extends Model
{
    protected $guarded = ['id'];

    public function rooms()
    {
        return $this->belongsToMany('App\Room')->withTimestamps();
    }
}

I can get all the amenities in the rooms in more detail:

$room = Room::with('amenities')->with('roomtype')
                        ->with('image')->Where('hotel_id', $hotel->id)->get();

This will provide convenience for each room, so I can go through all the rooms and get amenities

@foreach($room as $row)
    @foreach($row->amenities as $amenity)
        {{ $amenity->name }}
    @endforeach
@endforeach

Problem: I want excellent amenities, for example, many rooms may have wifi amenities. but i want it only once? how can i achieve this?

+4
source share
1 answer

Use the method whereHas():

$amenities = Amenities::whereHas('room', function($q) use($hotel) {
    $q->where('hotel_id', $hotel->id);
})
->get();

Or you can use the downloaded data. Just experienced this, works great:

$amenities = $room->pluck('amenities')->flatten()->unique('id');
+4

Source: https://habr.com/ru/post/1693688/


All Articles