Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Question] Duplicate insertion with custom primary key #2117

Answered by divine
amirasyraf asked this question in Q&A
Discussion options

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?

You must be logged in to vote

Hello,

Have you created correct index within mongodb itself?

Thanks!

Replies: 1 comment 4 replies

Comment options

Hello,

Have you created correct index within mongodb itself?

Thanks!

You must be logged in to vote
4 replies
Comment options

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.

Comment options

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?

Comment options

Yep, I did create a unique index:

db.mycollection.createIndex({customKey: 1}, {unique: true})

Definitely can still insert duplicate keys.

Comment options

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.

Answer selected by divine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #2117 on October 10, 2020 10:19.

AltStyle によって変換されたページ (->オリジナル) /