【发布时间】:2016-05-29 22:23:32
【问题描述】:
我需要延迟加载一些具有自定义顺序的相关模型。比如:
$season->load(['championships' => function ($query) {
$query->orderBy('country', 'desc');
}]);
但问题是锦标赛没有国家属性。在锦标赛模型中,我使用 getCountryAttribute 函数:
public function getCountryAttribute()
{
return $this->masterChampionship->country;
}
public function masterChampionship()
{
return $this->belongsTo('App\MasterChampionship');
}
我得到下一个结果:
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)
如果我不在控制器中使用 load 并从刀片模板访问冠军
@foreach($season->championships->sortBy('country') as $championship)
....
@endforeach
一切正常。但我想清理模板并将逻辑移动到控制器。有没有可能使用内置的 laravel 功能来解决我的问题,而无需构建自定义 BD 查询。
【问题讨论】:
标签: php laravel model laravel-5