我正在尝试将数据附加到我的3向透视表(由user_id、respondent_id和company_id组成,它们加在一起就是复合主键)。
当数据已经存在于表中时,我得到一个重复的键消息(duh)
我试图通过使用syncWithoutDetaching来防止这种情况,但它仍然抛出重复的密钥消息
我尝试做的事情如下:
class Respondent extends Authenticatable
{
public function companies()
{
return $this->belongsToMany('App\Models\Company', 'company_user_respondent');
}
public function attachPivot($company_id, $user_id)
{
//This will attach but if the keys exist it will send a duplication error
return $this->companies()->attach($company_id, ['user_id' => $user_id]);
}
}此外,我使用attachPivot方法尝试了这一点
public function attachPivot($company_id, $guide_id)
{
//Will allso send a duplication error, using just sync works but of course it will clean up my table which is not the goal.
return $this->companies()->syncWithoutDetaching([1 => ['company_id' => $company_id, 'guide_id' => $guide_id]]);
}如果记录存在,我可以检查我的数据库,但每次执行查询并不是我想要的目标,我想要的目标是在不抛出错误的情况下插入任何记录,或者在不分离的情况下同步表。
https://stackoverflow.com/questions/47569877
复制相似问题