laravel 以雄辩的关系排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37516509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order by for relationship in eloquent
提问by Paulinho Campello
I have a tables:
我有一张桌子:
- Analyses, columns(
id, name, game_id(FK)
); - Games, columns(
id, name, round_id(FK)
); - Round, columns(
id, round
);
- 分析,列(
id, name, game_id(FK)
); - 游戏、栏目(
id, name, round_id(FK)
); - 圆、柱(
id, round
);
I need get all records of Analyses order by (round_id
).
我需要按 ( round_id
)获取分析订单的所有记录。
I try Analyses::orderBy('round_id')->get()
, but not work;
我试了Analyses::orderBy('round_id')->get()
,但不行;
回答by Achraf Khouadja
First of all, you dont have that column in your analyses table
首先,您的分析表中没有该列
to do the orderby you have to add this to your relation (assuming they are correctly done)
要执行 orderby,您必须将其添加到您的关系中(假设它们已正确完成)
Analyses model
分析模型
public function games()
{
return $this->hasMany(Game::class)->orderBy('round_id'); //see? we can add orderBy to the relation
}
Games model
游戏模型
public function rounds()
{
return $this->hasMany(Round::class); // i dont know if its manytomany for eal, im just trying to explain
}
Now you can get all the Analyses with the games and round using eagerloading like this
现在,您可以像这样使用 Eagerloading 获得所有游戏分析和回合
$test = Analyses::with('games.round')->get();
you can chain another orderby for Analyses like this for exemple
例如,您可以像这样链接另一个 orderby 进行分析
$test = Analyses::with('games.round')->orderby('game_id')->get();
in the above exemple , you will have Analyses ordered by game_id and the games inside each Analyse will be orderedby round_id
在上面的示例中,您将按 game_id 排序分析,每个分析中的游戏将按 round_id 排序
I hope this is what you want to do
我希望这是你想做的
回答by Hamza Dairywala
Set the following relationships in to the respective model as given below
Analyses model
分析模型
Round Model
圆形模型
public function games()
{
return $this->hasMany('Game','game_id','id');
}
Game Model
游戏模型
public function analyses()
{
return $this->hasMany('Analyses','round_id','id');
}
Your Query Should be like This
你的查询应该是这样的
$round_game_wise_analyses= Round::with(['game'=>function($query){
$query->select()
->with(['analyses'=>function($query){
$query->select();
}]);
}])->orderBy('id','asc')->get();