Laravel 5.5 BelongsToMany与枢轴条件

时间:2019-01-04 15:58:52

标签: php laravel eloquent laravel-5.5

我有三个模型,ClinicDepartmentClinicDepartment,并且具有从belongsToMany到{{1}的departments关系,称为Clinic }使用Department的表作为数据透视表,但是当我使用此关系时,ClinicDepartment的范围在查询中不起作用。

我决定制作调用ClinicDepartment的Pivot模型,并将这些范围应用于Pivot,但是没有运气。

诊所模式:

ClinicDepartmentPivot

部门模型:

class Clinic extends Model
{
    use SoftDeletes, ActiveOnly, HasParent;

    public function departments()
    {
        return $this->belongsToMany(Department::class, 'clinic_departments', 'clinic_id', 'department_id')->using(ClinicDepartmentPivot::class);
    }
}

ClinicDepartmentPivot模型:

class Department extends Model
{
    use SoftDeletes, ActiveOnly;

    public function clinics()
    {
        return $this->belongsToMany(Clinic::class, 'clinic_departments', 'department_id', 'clinic_id')->using(ClinicDepartmentPivot::class);
    }
}

ActiveOnlyScope:

class ClinicDepartmentPivot extends Pivot
{
    use ActiveOnly, SoftDeletes;
}

因此,基本上我想将全局范围应用于Pivot模型,因此,当我尝试获取Department Clinics时,应检查-ClinicDepartment是否具有class ActiveOnlyScope implements Scope { public function apply(Builder $builder, Model $model) { $builder->where($model->getTable() . '.is_active', true); } } 并且未被删除。

UPD 1

我的范围特征如下:

is_active = 1

可用于任何型号。

2 个答案:

答案 0 :(得分:0)

您在这里缺少了一些东西

  

要将全局范围分配给模型,您应该覆盖给定的   模型的启动方法,并使用addGlobalScope方法

Laravel Docs on scope

您的模型应如下所示:

class Clinic extends Model
{
    use SoftDeletes, ActiveOnly, HasParent;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new ActiveOnlyScope);
    }

    public function departments()
    {
        return $this->belongsToMany(Department::class, 'clinic_departments', 'clinic_id', 'department_id')->using(ClinicDepartmentPivot::class);
    }
}



class Department extends Model
{
    use SoftDeletes, ActiveOnly;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new ActiveOnlyScope);
    }

    public function clinics()
    {
        return $this->belongsToMany(Clinic::class, 'clinic_departments', 'department_id', 'clinic_id')->using(ClinicDepartmentPivot::class);
    }
}

答案 1 :(得分:0)

好吧,有了一些解决方法,我终于找到了看起来不那么草率的可行解决方案)

public function clinics()
    {
        return $this->belongsToMany(Clinic::class, 'clinic_departments', 'department_id', 'clinic_id')
            ->where(function (Builder $query) {
                $query->where('clinic_departments.is_active', 1)
                    ->whereNull('clinic_departments.deleted_at');
            });
    }

实际查询如下:

select `clinics`.*, `clinic_departments`.`department_id` as `pivot_department_id`, `clinic_departments`.`clinic_id` as `pivot_clinic_id` from `clinics` inner join `clinic_departments` on `clinics`.`id` = `clinic_departments`.`clinic_id` where (`clinic_departments`.`is_active` = 1 and `clinic_departments`.`deleted_at` is null)

谢谢大家的想法。