You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9中如何按嵌套关联模型字段排序查询记录?

按关联的Department标题排序LicenseSubmissions的实现方法

Eloquent 实现方式

方法1:使用 join 连表排序

直接通过join关联多层关联表,指定排序字段:

$submissions = LicenseSubmission::join('license_forms', 'license_submissions.license_form_id', '=', 'license_forms.id')
    ->join('departments', 'license_forms.department_id', '=', 'departments.id')
    ->select('license_submissions.*') // 明确选择主表字段,避免重名字段冲突
    ->orderBy('departments.title', 'asc') // 替换为'desc'可实现降序
    ->get();

方法2:使用 orderByRaw 关联排序

无需显式连表,通过子查询指定排序逻辑:

$submissions = LicenseSubmission::orderByRaw('(SELECT title FROM departments WHERE id = (SELECT department_id FROM license_forms WHERE id = license_submissions.license_form_id)) asc')
    ->get();

注:该方式代码更简洁,但数据量较大时性能不如join方案,需根据场景选择。

方法3:全局作用域(频繁排序场景)

如果需要频繁按部门标题排序,可在LicenseSubmission模型中定义全局作用域:

// LicenseSubmission 模型文件
protected static function booted()
{
    static::addGlobalScope('sortByDepartment', function ($query) {
        $query->join('license_forms', 'license_submissions.license_form_id', '=', 'license_forms.id')
            ->join('departments', 'license_forms.department_id', '=', 'departments.id')
            ->select('license_submissions.*')
            ->orderBy('departments.title', 'asc');
    });
}

之后直接查询会自动应用排序:

$submissions = LicenseSubmission::get();

原生SQL 实现方式

编写原生SQL连表查询,在Laravel中通过DB::select()执行:

$submissions = DB::select("
    SELECT ls.*
    FROM license_submissions ls
    JOIN license_forms lf ON ls.license_form_id = lf.id
    JOIN departments d ON lf.department_id = d.id
    ORDER BY d.title ASC
");

内容的提问来源于stack exchange,提问作者Rayan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:52:45