【发布时间】:2017-11-30 09:23:46
【问题描述】:
我正在尝试将数据附加到我的 3 向数据透视表(由 user_id、responent_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]]);
}
如果记录存在,我可以检查我的数据库,但每次都进行查询不是我想要的目标,我想要的目标是不会插入任何记录而不抛出错误或同步表而不分离。
【问题讨论】:
标签: php mysql laravel eloquent