【问题标题】:Laravel 5.5; Duplicate entry on 3-way pivot table with 3 composite primary keyLaravel 5.5;具有 3 个复合主键的 3 向数据透视表上的重复条目
【发布时间】: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


    【解决方案1】:

    发现我可以通过执行以下操作来防止这种情况

    try {
        return $this->companies()->attach($company_id, ['user_id' => $user_id]);
    } catch (QueryException $exception) {
        return $exception;
    }
    

    现在它将返回我可以检查或附加指定值的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 2014-09-16
      • 2016-09-04
      • 2020-07-22
      • 2018-07-06
      • 1970-01-01
      • 2010-10-24
      相关资源
      最近更新 更多