Integrity constraint violation: 1062 Duplicate entry using updateOrCreate Hi all,
I have:
Preconsult::updateOrCreate([
'company_id' => company(),
'pet_id' => $pet_id
], [
'body' => request('preconsult_text')
]);
But it gives an error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '27-375777' for key 'company-pet' (SQL: insert into `preconsults` (`company_id`, `pet_id`, `body`, `updated_at`, `created_at`) values (27, 375777, <p>Revision</p>, 2024-04-24 17:02:02, 2024-04-24 17:02:02))
Do you have any clue
Thanks in advance for your time
Could you share your migration?
Sure @danteb918
Schema::create('preconsults', function (Blueprint $table) {
$table->primary(['company_id', 'pet_id']);
$table->unsignedInteger('company_id');
$table->unsignedInteger('pet_id');
$table->text('body');
$table->timestamps();
});
Eloquent does not support composite primary key tables, thus Laravel doesn't
https://github.com/laravel/framework/discussions/48152 <- here's an issue from 8 months ago on the Laravel repository about the topic.
And Taylor Otwell has stated here that he does not plan to support it. https://github.com/laravel/framework/issues/5355#issuecomment-115426172
What I would do if I were you, is remove the composite keys and update your migration like so:
Schema::create('preconsults', function (Blueprint $table) {
$table->unsignedInteger('company_id');
$table->unsignedInteger('pet_id');
$table->text('body');
$table->timestamps();
//Not sure the actual names of these tables and the col name of the PK's
$table->foreign('company_id')->references('id')->on('companies');
$table->foreign('pet_id')->references('id')->on('pets');
});
@danteb918 thank for your time.
I've already changed them in the table, this the current table:
CREATE TABLE `preconsults` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`company_id` int(10) unsigned NOT NULL,
`pet_id` int(10) unsigned NOT NULL,
`history_id` int(10) unsigned DEFAULT NULL,
`body` text NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `company-pet` (`company_id`,`pet_id`)
) ENGINE=InnoDB AUTO_INCREMENT=151418 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Please sign in or create an account to participate in this conversation.