When using the belongsToMany
relation in Laravel Eloquent, is it possible to add additional conditions for the intermediate table? Currently, the inserts are duplicating and I am just trying to understand how to fix it.
Here is the relation
Models/Order.php
public function addresses(): BelongsToMany
{
return $this->belongsToMany(CustomerAddress::class)
->withPivot('address_type')
->withTimestamps();
}
Here is how I save the data to the intermediate table
$tenantOrder-addresses()->attach($customerAddress->id, [
'address_type' => 'billing'
]);
Do I need to do anything else to prevent the duplicates? Below is the example of showing the duplicates. The combination being customer_address_id, order_id, address_type
.
CodePudding user response:
If you mean to prevent duplicate on pivot table, can add composite keys on pivot table migrations
Something like this
...
$table->primary(['customer_address_id', 'order_id', 'address_type']);
That will prevent adding new row if the customer, order, and address type in a same value.
Here's a test
CodePudding user response:
I believe you are looking for syncWithoutDetaching
. It helps attach
without duplicated record.
Reference: https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations