Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updateOrCreate -> createOrFirst doesn't work as expected #2945

Closed
Boevsson opened this issue May 14, 2024 · 3 comments
Closed

updateOrCreate -> createOrFirst doesn't work as expected #2945

Boevsson opened this issue May 14, 2024 · 3 comments

Comments

@Boevsson
Copy link

Boevsson commented May 14, 2024

  • Laravel-mongodb Version: 4.2
  • PHP Version: 8.3.4
  • Database Driver & Version: mongod 5.0 / 7.0

Description:

Steps to reproduce

  1. $id = $request->get('id') ?? null; // in the case id is null
  2. Do Model::updateOrCreate(['_id' => $id], $data);

Expected behaviour

A new record should be created with the given data and a generated _id.

Actual behaviour

It queries the first record from the collection and updates it.

This works fine when using the package 4.0 because the createOrFirst is not overriden there in the Mongo Builder class

@GromNaN
Copy link
Member

GromNaN commented May 20, 2024

Thanks for the report.
Related to #2935
Tracked in Jira PHPORM-183

@GromNaN GromNaN closed this as not planned Won't fix, can't repro, duplicate, stale May 20, 2024
@GromNaN GromNaN reopened this May 20, 2024
@GromNaN
Copy link
Member

GromNaN commented May 22, 2024

After investigation, null is a valid value for MongoDB _id. That's why the Model::updateOrCreate(['_id' => null], $data) creates or updates a new document with _id: null.

This is inconsistent with how SQL works because SQL databases will generate a value with a request like this: INSERT INTO table (id, name) VALUES (null, 'foo').

Can you modify your code like this:

$id = $request->get('id'); // null is the default value
if ($id) {
    $model = Model::updateOrCreate(['_id' => $id], $data);
} else {
    $model = Model::create($data);
}

@GromNaN
Copy link
Member

GromNaN commented May 28, 2024

Closing as this is the expected behavior for MongoDB.

@GromNaN GromNaN closed this as not planned Won't fix, can't repro, duplicate, stale May 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants