我有两张表 - 医生和部门以及他们之间的关系医生_有_部门。
我想添加一个布尔 isBoss 列,但我不知道如何更改其中的值并在 laravel 中引用它。
我想做一个复选框,如果选中它会将值更改为 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
从您的问题来看,您似乎在医生和科室之间存在多对多关系,并且假设您有这些表格
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