如何在 Laravel 中通过嵌套关联关系实现 orderBy 排序

laravel 的 `orderby()` 无法直接对深层关联字段(如 `file.property.full_address`)排序,需改用 `join` 显式关联表并选择目标字段进行排序。

在 Laravel 中,with() 和 orderBy() 是两个独立机制:with() 用于懒加载或预加载关联数据(Eloquent 关系),而 orderBy() 仅作用于主查询表(此处为 finance_invoices)的字段。因此,像 ->orderBy("file.property.full_address") 这样的写法会触发 SQL 错误——因为数据库层面并不存在名为 file.property.full_address 的列,它只是 Eloquent 的关系路径表达式,并非真实 SQL 列名。

✅ 正确做法是使用 join 显式关联多张表,并在 orderBy() 中引用已 join 进来的字段:

$invoices = \App\Finance_Invoices::query()
    ->select('finance_invoices.*') // 显式指定主表字段,避免列冲突
    ->join('finance_files as file', 'file.id', '=', 'finance_invoices.file_id')
    ->join('properties as property', 'property.id', '=', 'file.property_id')
    ->join('landlords as landlord', 'landlord.id', '=', 'property.landlord_id')
    ->where('finance_invoices.period', '02')
    ->where('finance_invoices.year', '2025')
    ->where('finance_invoices.paid_to_landlord', 0)
    ->whereColumn('finance_invoices.total_paid', '>=', 'finance_invoices.amount')
    ->where('landlord.id', $id)
    ->orderBy('property.full_address')
    ->get();

? 注意事项:

  • 使用别名(如 as file、as property)提升可读性与避免歧义;
  • 必须确保外键关系正确(例如 finance_invoices.file_id → finance_files.id);
  • 若仍需获取完整关联模型(如 file, property, landlord 对象),可在 get() 后补充 load(),或结合 with() 与 join(但需注意 N+1 风险);
  • 若排序字段可能为 NULL,可加 ->orderByRaw('COALESCE(property.full_address, "")') 控制空值排序位置。

? 小结:Eloquent 不支持跨多层关系的 orderBy,本质是 SQL 层限制。用 join 构建扁平化查询,既保证排序可行性,又提升性能(避免多次查询)。这是处理“按深层关联字段排序”场景的标准实践。