I need some advice on the following.
I have 2 migrations, like so.
Schema::create('plates', function (Blueprint $table) {
$table->increments('id');
$table->integer('serial_number');
$table->string('crc-code', 50);
$table->string('reason', 50)->nullable();
$table->softDeletes();
$table->timestamps();
});
And another one
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 25)->unique();
$table->text('description')->nullable();
$table->longText('relative_path');
A pivot table for many to many relations I have setup just like this
Schema::create('document_plate', function (Blueprint $table) {
$table->integer('plate_id')->unsigned()->index();
$table->integer('document_id')->unsigned()->index();
$table->primary(['plate_id', 'document_id']);
$table->timestamps();
});
When taking a certain action I use the code below to attach a plate
to a document
$plate = Plate::find(1);
$doc = Document::find(1);
if($plate && $doc) {
$plate->documents()->attach($doc->id);
}
The first time, everything works just fine! the document_plate
gets updated. The error occurs when having the same ids
doing it again.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'PRIMARY' (SQL: insert into
document_plate
(created_at
,document_id
,plate_id
,updated_at
)
Now the question
Is there a way to avoid getting errors and just update the table with the same ids
??
Or.. I need to setup a some sort of validation on the front-end which tells the user (before submitting) that he/she choose the same id's
which are already in the table.
Note: I am using AngularJS for front-end operations.
Laravel makes this very simple to achieve by using the sync
method. The sync
method by default will detach any ids that you don't pass to it, but it accepts a second argument that can disable the detaching.
$plate->documents()->sync([$doc->id], false);
This will only add the entry if it does not already exist in the table.
Link to the API: http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Relations/BelongsToMany.html#method_sync
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments