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

它是一个酒店预订应用程序,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便利设施.但我只想要它一次?我怎么能实现这个目标?

解决方法:

使用whereHas()方法

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

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...