Laravel-与多对多相关的附加列

时间:2018-07-07 22:22:57

标签: php sql laravel voyager

我有两个表-医生和部门,以及它们之间的关系Doctor_has_department。

我想添加一个布尔值isBoss列,但是我不知道如何更改其中的值并在laravel中引用它。

我想做一个复选框,如果选中,它将值更改为1。

2 个答案:

答案 0 :(得分:1)

一旦您在数据透视表上添加了其他列,请更新该关系以使其也包括在内。示例:

public function department()
    {
        return $this->belongsToMany('App\Department')
            ->withPivot('is_boss')
            ->withTimestamps();
    }

public function doctors()
        {
            return $this->belongsToMany('App\Doctor')
                ->withPivot('is_boss')
                ->withTimestamps();
        }

然后您可以像这样查询它:

if $department->pivot->is_boss == 1

答案 1 :(得分:0)

从您的问题来看,似乎您与医生和科室之间存在ManyToMany关系,并且假设您拥有这些表

doctors(id, name ...)
departments(id, name ...)
department_doctor(id, doctor_id, department_id, is_boss ...) pivot table with is_boss pivot field and default laravel naming convention 

现在在模型中定义您的关系

医生模型

public function departments(){
    return $this->hasMany('App\Department', 'department_doctor')->withTimestamps(); //if you have different pivot table name then replace department_doctor
}

部门模型

public function doctors(){
    return $this->hasMany('App\Doctor', 'department_doctor')->withPivot('is_boss')->withTimestamps(); //if you have different pivot table name then replace department_doctor
}

现在插入

//get doctor id and is_boss from request
$doctorId = $request->input('doctor_id');
$isBoss = $request->input('is_boss');

//now save it using relation
$department = Department::find(1);
$department->doctors()->attach($doctorId, array('is_boss' => $isBoss));

有关详细信息,请https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

相关问题