这段关系怎么能做到这一点,这值得吗? (获取诊所的所有部门)

How can this be done with the relationship, and is it worth it? (Get all departments for clinic)

我有 3 个表:

诊所

部门

clinics_in_departments

使用查询生成器:

$department = ClinicsInDepartment::whereIn('clinic_id',[1,2,3])
            ->join('departments', 'clinics_in_departments.department_id', '=', 'departments.id')
            ->get();

这种关系怎么能做到,值得吗?

您可以在 Clinics 模型中定义属于多个关系,如下面的代码

 function departments(){
    return $this->belongsToMany('App\Clinics', 'clinics_in_departments');
 }

如果您在多对多部分 https://laravel.com/docs/5.6/eloquent-relationships#many-to-many 查看 Laravel 的文档,它已经在其中进行了解释。如果您打算继续使用 Laravel,我建议您使用 Eloquent 的最佳实践。其他开发人员更容易理解和阅读。尽你所能使你的产品最好总是值得的。它还提供了快速扩展和维护您的应用程序的可能性。

您需要做的就是在您的模型诊所中定义关系

// second, third and fourth parameter could also be optional
function departments(){
    return $this->belongsToMany('App\Clinics', 'clinics_in_departments', 'department_id', 'clinic_id');
}

要检索您可以使用的数据

$clinics = Clinics::with('departments')->get();
// this would hold a list of departments for each clinic

要获得完全相同的数据,请将查询扩展到此

$clinics = Clinics::with('departments')->whereIn('clinic_id',[1,2,3])->get();

因为它是多对多关系,您还可以为模型 Departments 定义一个关系,并执行与上述完全相同的操作。