RelationManager select relationship with multiple(), Duplicate entry on update
Hi, the following code in a RelationManager:
public function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make()
->schema([
Forms\Components\Select::make('domains')
->relationship('domains','domain')
->multiple()
->preload(),
With a belongsToMany from both Models to each other. When creating, there is no problem, but when updating and add more domains, I get:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'assets_content_domain.PRIMARY'
insert into assets_content_domain
(assets_content_id
, domain_id
) values (1, 2)
Shouldn't it automatically manage that the record I am updating already exists? It's a bug?
ThanksSolution:Jump to solution
Ahh I see you have a primary key set on assets_content_id and you are setting it wrong for a composite primary key. Try:
```php...
7 Replies
π©
can you provide your relationship?
Hi, sure:
class Domain extends Model:
public function assets_contents()
{
return $this->belongsToMany(AssetsContent::class);
}
class AssetsContent extends Model:
public function image()
{
return $this->belongsTo(Image::class);
}
And the pivot migration:
Schema::create('assets_content_domain', function (Blueprint $table) {
$table->unsignedInteger('assets_content_id');
$table->foreign('assets_content_id')->references('id')->on('assets_contents');
$table->unsignedTinyInteger('domain_id');
$table->foreign('domain_id')->references('id')->on('domains');
$table->primary('assets_content_id','domain_id');
});
You need to so the assets_contents using a pivot so surely
should be
The pivot should mean you remove/add the values instead of trying to insert them
Thanks for the reply, but the withPivot() method is not necessary if the pivot table doesn't have any additional columns besides the foreign keys:
In Laravel, when you define a many-to-many relationship using belongsToMany(), Laravel will automatically handle the foreign keys in the pivot table.Any other idea?
Solution
Ahh I see you have a primary key set on assets_content_id and you are setting it wrong for a composite primary key. Try:
Well spotted! Solved π