简体   繁体   English

laravel Lazy Eager与orderBy相关模型加载

[英]laravel Lazy Eager Loading with orderBy related model

I need to lazy eager load some related models with custom order. 我需要懒洋洋地渴望用自定义顺序加载一些相关模型。 Something like: 就像是:

$season->load(['championships' => function ($query) {
    $query->orderBy('country', 'desc');
}]);

But the problem is that championships do not have country property. 但是问题是冠军没有乡村财产。 In Championship model I use getCountryAttribute function: 在冠军赛模型中,我使用getCountryAttribute函数:

public function getCountryAttribute()
{
    return $this->masterChampionship->country;
}

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

And I get next results: 我得到下一个结果:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country' in 'order clause' (SQL: select * from `championships` where `championships`.`season_id` in (41) order by `country` desc)

If i don't use load in controller and access championships from blade template 如果我不使用控制器中的负载并从刀片模板访问冠军

@foreach($season->championships->sortBy('country') as $championship)
    ....
@endforeach

everything works fine. 一切正常。 But I want to cleanup template and move logic to controller. 但是我想清理模板并将逻辑移到控制器。 Is there any possibility to solve my case using built-in laravel features, without building custom BD query. 是否有可能使用内置的laravel功能解决我的问题,而无需构建自定义BD查询。

Youll have to change the table names, as I don't know what they are, but I think this would work: 您必须更改表名,因为我不知道它们是什么,但是我认为这可以工作:

$season->load(['championships' => function($query){

    $query->select('championships.*')
        ->join('master_championships', 'championships.master_championships_id', '=', 'master_championships.id')
        ->orderBy('master_championships.country', 'desc');

}]);

I don't think you can order the query without using a join, seeing as you have to access the third table to get the country attribute. 我认为您必须不使用联接就可以对查询进行排序,因为您必须访问第三个表才能获得country属性。 You may save a bunch of queries from hitting the database if you do 如果这样做,您可以保存许多查询以免打入数据库

$season->load(['championships','championships.masterChampionships']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM