laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

updateOrCreate method always creates a new model

Open sam-script opened this issue 2 years ago • 0 comments

  • Laravel-mongodb Version: 3.8.4
  • Laravel Version: v8.50.0
  • PHP Version: 7.4.13
  • Database Driver & Version: mongodb/mongodb 1.9.0

Description:

The eloquent method updateOrCreate will always create a new model, rather than update the model if it is already persisted.

Steps to reproduce

  1. Model::updateOrCreate(['foo' => $bar, 'bar' => $foo]);

Expected behaviour

If there is a model with matching attributes, they will be updated. If there isn't a matching model, it should be created.

Actual behaviour

A new model was constantly creating resulting in many duplicates.

Steps to fix

Created a new base model MongoModel which extends Jenssegers\Mongodb\Eloquent\Model. In MongoModel, I created a new method to overwrite the updateOrCreate method using the solution mentioned in #1836 by @styper. All my new models will extend MongoModel so that the new updateOrCreate method can be carried over.

sam-script avatar Jul 21 '21 15:07 sam-script