【问题标题】:laravel Lazy Eager Loading with orderBy related modellaravel Lazy Eager Loading with orderBy 相关模型
【发布时间】: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


    【解决方案1】:

    您必须更改表名,因为我不知道它们是什么,但我认为这可行:

    $season->load(['championships' => function($query){
    
        $query->select('championships.*')
            ->join('master_championships', 'championships.master_championships_id', '=', 'master_championships.id')
            ->orderBy('master_championships.country', 'desc');
    
    }]);
    

    我认为您不能在不使用连接的情况下对查询进行排序,因为您必须访问第三个表才能获得 country 属性。如果你这样做,你可以节省一堆查询到数据库

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

    【讨论】:

    • 一切正常。表名和列名的一些错误 Champions.master_championships_id -> Championships.master_championship_id master_championships.country -> master_championships.country_id
    猜你喜欢
    • 2017-06-28
    • 2018-02-24
    • 2020-11-09
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多