F
Filamentβ€’4mo ago
ffffer.

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? Thanks
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...
Jump to solution
7 Replies
ffffer.
ffffer.OPβ€’4mo ago
😩
toeknee
toekneeβ€’4mo ago
can you provide your relationship?
ffffer.
ffffer.OPβ€’4mo ago
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'); });
toeknee
toekneeβ€’4mo ago
You need to so the assets_contents using a pivot so surely
public function assets_contents()
{
return $this->belongsToMany(AssetsContent::class);
}
public function assets_contents()
{
return $this->belongsToMany(AssetsContent::class);
}
should be
public function assets_contents()
{
return $this->belongsToMany(AssetsContent::class)->withPivot();
}
public function assets_contents()
{
return $this->belongsToMany(AssetsContent::class)->withPivot();
}
The pivot should mean you remove/add the values instead of trying to insert them
ffffer.
ffffer.OPβ€’4mo ago
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
toeknee
toekneeβ€’4mo ago
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:
$table->primary(['assets_content_id', 'domain_id']);
$table->primary(['assets_content_id', 'domain_id']);
ffffer.
ffffer.OPβ€’4mo ago
Well spotted! Solved πŸ™‚
Want results from more Discord servers?
Add your server