如何在Laravel中通过嵌套关系的列获得记录顺序?

qxsslcnc  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(74)

我用的是Laravel 9。为了澄清我的问题,我将解释模型以及它们之间的关系。
第一个模型是LicenseSubmission,它与LicenseForm模型有one to many关系:

class LicenseSubmission extends Model
{

    public function licenseForm(): BelongsTo
    {
        return $this->belongsTo(LicenseForm::class);
    }
}

此外,LicenseForm模型与Department模型之间存在one to many关系:

class LicenseForm extends Model
{

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }
  
}

现在我想得到license_submissions的命令,由其相关部门的标题。
如何做到这一点?
如果你能回答这个问题,那么Eloquent代码和RawSQL之间没有区别。

1u4esq0p

1u4esq0p1#

试试这个:

LicenseSubmission::with('licenseForm.department')
    ->orderBy('licenseForm.department.title')
    ->get();

相关问题