2015-06-02 29 views
0

我有一个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'); 
} 

回答

0

在模型的关系方法中包含其他查询构建步骤并不是一个很好的做法。关系方法应该只是定义关系,没有别的。更清洁的方法是申请eager load constraints。 (向下滚动)考虑以下内容。

Hotels::where('id', 200)->with(array(
    'distance' => function ($query) 
    { 
     $query->withPivot('id')->orderBy('pivot_id','desc'); 
    }, 
    'type' => function ($query) 
    { 
     $query->withPivot('id')->orderBy('pivot_id','desc'); 
    }, 
))->take(5)->get(); 

如果你发现你经常踊跃加载以这种方式这个关系,可以考虑使用scopes让事情变得干燥。最终结果将允许你做这样的事情。

Hotels::where('id', 200)->withOrderedDistance()->withOrderedType()->take(5)->get(); 

P.S.你的模型应该是单一的。酒店,而不是酒店。该模型代表单个记录。

+0

有趣的,不知道你可以这样做。感谢你的帮助。我想我会使用一个范围,因为它会经常使用。 – limit

0

通过使用解决 - > withPivot( 'ID') - > ORDERBY( 'pivot_id', '递减');

在问题中发布答案。