Laravel只从相关模型中选择不同的值(多对多关系)

时间:2018-02-15 12:17:10

标签: php mysql laravel laravel-5.5

它是一个酒店预订应用程序,1个酒店可能有很多房间,一个房间可能有很多设施(设施)。

我的模型是这样的:

会议室型号:

class Room extends Model
{

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

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

}

设施型号:

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

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

我可以通过以下查询获得每个房间的设施:

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

这将为每个房间提供便利设施,因此我可以遍布每个房间并获得便利设施

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

问题: 我想要不同的设施,例如许多房间可能有 wifi 设施。但我只想要它一次?我怎么能做到这一点?

1 个答案:

答案 0 :(得分:4)

使用whereHas()方法:

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

或者,您可以使用加载的数据。刚试过这个,效果很好:

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