2017-11-30 20 views
0

3ウェイピボットテーブル(複合主キーであるuser_id、respondent_id、およびcompany_idで構成)にデータを添付しようとしています。Laravel 5.5;

データはすでに私が重複するキーメッセージ(当たり前)

を取得し、テーブルに存在する場合、私は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]); 
    } 
} 

またIは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]]); 
} 
でこれを試みました210

レコードが存在するが、毎回クエリを実行するのが私の望ましい目標ではないことを私のDBで確認できました。私の望ましい目標は、エラーをスローせずにレコードを挿入したり、

答えて

0

は、私は今では私が指定した値をチェックしたり、添付することができ、例外のいずれかを返します。次

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

をすることによって、これを防ぐことができることが分かりました。