我正在尝试在数据透视关系中使用同步方法,但是它无法正确保存数据。
organization_id
和user_id
用户
public function organization()
{
return $this->hasOne(Organization::class, 'superAdmin_id', 'id');
}
public function organizationAdmins()
{
return $this->hasOne(OrganizationAdmin::class, 'organization_admins', 'user_id', 'id');
}
组织
public function superAdmin()
{
return $this->belongsTo(User::class, 'superAdmin_id', 'id');
}
public function admins()
{
return $this->belongsToMany(OrganizationAdmin::class, 'organization_admins', 'organization_id', 'id');
}
OrganizationAdmin
public function organization()
{
return $this->belongsToMany(Organization::class, 'organization_admins', 'id', 'organization_id');
}
public function user()
{
return $this->belongsTo(User::class);
}
控制器
public function update(Request $request, $id)
{
//...
$organization->save();
$admins = $request->input('user_id');
$organization->admins()->sync($admins); //saving admins in pivot table
}
结果
这是保存在数据库中的内容用户的信息不会保存
有什么想法吗?
答案 0 :(得分:1)
解决此问题
组织
public function admins()
{
return $this->belongsToMany(OrganizationAdmin::class, 'organization_admins', 'organization_id', 'user_id');
}
答案 1 :(得分:0)
使用此
public function admins()
{
return $this->belongsToMany(OrganizationAdmin::class, 'organization_admins', 'organization_id', 'user_id')->withTimestamps();
}
有关更多信息,请阅读Many to many eloquent relationships