-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[Question] Duplicate insertion with custom primary key #2117
-
Hi,
Lets say I have the following model:
<?php
class Order extends Model
{
use HasFactory;
protected $connection = 'mongodb';
protected $primaryKey = 'customKey';
protected $guarded = [];
}
Then,
// First insert
$order = Order::create([
'customKey' => 'key1',
'data' => $data,
]);
// Second insert
$order = Order::create([
'customKey' => 'key1',
'data' => $data,
]);
The second insert is still successful despite it having the same customKey key1
which already exists. I thought with the primary key defined, it would throw an error (or ignore) when inserting a duplicate key? Is this not the case?
I don't think insertOrIgnore
is supported either. Any alternative solution to this?
Beta Was this translation helpful? Give feedback.
All reactions
Hello,
Have you created correct index within mongodb itself?
Thanks!
Replies: 1 comment 4 replies
-
Hello,
Have you created correct index within mongodb itself?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions
-
I wasn't aware I needed to create the index manually first. But I have tried it just now and I'm still able to insert the duplicate key.
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions
-
This is a database, you should create indexes (or in laravel schemas and import it).
Have you created a unique index or just plain one?
Beta Was this translation helpful? Give feedback.
All reactions
-
Yep, I did create a unique index:
db.mycollection.createIndex({customKey: 1}, {unique: true})
Definitely can still insert duplicate keys.
Beta Was this translation helpful? Give feedback.
All reactions
-
Double check that you've created correctly it.
If you're still able to create duplicate keys then you're doing something wrong with your database.
Not related to this library at all.
Beta Was this translation helpful? Give feedback.