我有一个Pivot表,它用于连接两个其他表,每个hotel_id有许多关系。有没有一种方法可以在一种关系中提高两个表的结果?原始SQL查询正常工作,但在使用belongsToMany时,订单已关闭。Laravel Eager Load和Group Multiple Joins Pivot
设施透视表
id
hotel_id
distance_id
type_id
距离表
id
name
类型表
id
name
原始查询(这工作正常)
SELECT * FROM amenities a
LEFT JOIN distance d ON a.distance_id = d.id
LEFT JOIN type t ON a.type_id = t.id WHERE a.hotel_id = ?
我的“酒店”模型是使用belongsToMany像这样
public function distance() {
return $this->belongsToMany('Distance', 'amenities', 'hotel_id', 'distance_id');
}
public function type() {
return $this->belongsToMany('Type', 'amenities', 'hotel_id', 'type_id');
}
它输出的收集,但他们没有正确分组。我需要在透视表中输入并排选择字段,因此用户可以选择“类型”和“距离”,但是在使用集合时订单已关闭。上面的原始查询输出正确。
Hotels::where('id','=','200')->with('distance', 'type')->take(5)->get();
好的解决了它。所以显然你可以在你的数据透视表上使用orderBy。因为任何人都有这个问题,这是我在两个关系上所做的。
public function distance() {
return $this->belongsToMany('Distance', 'amenities', 'hotel_id', 'distance_id')->withPivot('id')->orderBy('pivot_id','desc');
}
public function type() {
return $this->belongsToMany('Type', 'amenities', 'hotel_id', 'type_id')->withPivot('id')->orderBy('pivot_id','desc');
}
有趣的,不知道你可以这样做。感谢你的帮助。我想我会使用一个范围,因为它会经常使用。 – limit