Skip to content

Commit ca91f03

Browse files
committed
-
1 parent 7e72c2c commit ca91f03

File tree

4 files changed

+126
-34
lines changed

4 files changed

+126
-34
lines changed

src/Eloquent/Builder.php

Lines changed: 4 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use function array_intersect_key;
1919
use function array_key_exists;
2020
use function array_merge;
21+
use function assert;
2122
use function collect;
2223
use function is_array;
2324
use function iterator_to_array;
@@ -216,41 +217,10 @@ public function createOrFirst(array $attributes = [], array $values = []): Model
216217

217218
// Apply casting and default values to the attributes
218219
// In case of duplicate key between the attributes and the values, the values have priority
219-
$instance = $this->newModelInstance($values + $attributes);
220+
$instance = $this->newModelInstance(array_merge($attributes, $values));
221+
assert($instance instanceof Model);
220222

221-
/* @see \Illuminate\Database\Eloquent\Model::performInsert */
222-
if ($instance->usesTimestamps()) {
223-
$instance->updateTimestamps();
224-
}
225-
226-
$values = $instance->getAttributes();
227-
$attributes = array_intersect_key($attributes, $values);
228-
229-
return $this->raw(function (Collection $collection) use ($attributes, $values) {
230-
$listener = new FindAndModifyCommandSubscriber();
231-
$collection->getManager()->addSubscriber($listener);
232-
233-
try {
234-
$document = $collection->findOneAndUpdate(
235-
$attributes,
236-
// Before MongoDB 5.0, $setOnInsert requires a non-empty document.
237-
// This should not be an issue as $values includes the query filter.
238-
['$setOnInsert' => (object) $values],
239-
[
240-
'upsert' => true,
241-
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
242-
'typeMap' => ['root' => 'array', 'document' => 'array'],
243-
],
244-
);
245-
} finally {
246-
$collection->getManager()->removeSubscriber($listener);
247-
}
248-
249-
$model = $this->model->newFromBuilder($document);
250-
$model->wasRecentlyCreated = $listener->created;
251-
252-
return $model;
253-
});
223+
return $instance->save(['find_or_insert' => $attributes]);
254224
}
255225

256226
/**

src/Eloquent/Model.php

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,35 @@ protected function isBSON(mixed $value): bool
746746
*/
747747
public function save(array $options = [])
748748
{
749+
// create_or_first contains the list of fields to check for duplicates
750+
if (isset($options['create_or_first'])) {
751+
$query = $this->newModelQuery();
752+
753+
// If the "saving" event returns false we'll bail out of the save and return
754+
// false, indicating that the save failed. This provides a chance for any
755+
// listeners to cancel save operations if validations fail or whatever.
756+
if ($this->fireModelEvent('saving') === false) {
757+
return false;
758+
}
759+
760+
// If the model already exists in the database we can just update our record
761+
// that is already in this database using the current IDs in this "where"
762+
// clause to only update this model. Otherwise, we'll just insert them.
763+
if ($this->exists) {
764+
$saved = $this->isDirty() ?
765+
$this->performUpdate($query) : true;
766+
$instance = $this;
767+
} else {
768+
['inserted' => $inserted, 'document' => $document] = $this->performFindOrInsert($query, $options['create_or_first']);
769+
if ($inserted) {
770+
$keyName = $this->getKeyName();
771+
$this->setAttribute($keyName, $document[$keyName]);
772+
773+
return $this;
774+
}
775+
}
776+
}
777+
749778
$saved = parent::save($options);
750779

751780
// Clear list of unset fields
@@ -766,4 +795,53 @@ public function refresh()
766795

767796
return $this;
768797
}
798+
799+
private function performFindOrInsert(Builder $query, array $filter)
800+
{
801+
if ($this->usesUniqueIds()) {
802+
$this->setUniqueIds();
803+
}
804+
805+
if ($this->fireModelEvent('creating') === false) {
806+
return false;
807+
}
808+
809+
// First we'll need to create a fresh query instance and touch the creation and
810+
// update timestamps on this model, which are maintained by us for developer
811+
// convenience. After, we will just continue saving these model instances.
812+
if ($this->usesTimestamps()) {
813+
$this->updateTimestamps();
814+
}
815+
816+
// If the model has an incrementing key, we can use the "insertGetId" method on
817+
// the query builder, which will give us back the final inserted ID for this
818+
// table from the database. Not all tables have to be incrementing though.
819+
$attributes = $this->getAttributesForInsert();
820+
821+
if ($this->getIncrementing()) {
822+
$this->insertAndSetId($query, $attributes);
823+
}
824+
825+
// If the table isn't incrementing we'll simply insert these attributes as they
826+
// are. These attribute arrays must contain an "id" column previously placed
827+
// there by the developer as the manually determined key for these models.
828+
else {
829+
if (empty($attributes)) {
830+
return true;
831+
}
832+
833+
$query->insert($attributes);
834+
}
835+
836+
// We will go ahead and set the exists property to true, so that it is set when
837+
// the created event is fired, just in case the developer tries to update it
838+
// during the event. This will allow them to do so and run an update here.
839+
$this->exists = true;
840+
841+
$this->wasRecentlyCreated = true;
842+
843+
$this->fireModelEvent('created', false);
844+
845+
return true;
846+
}
769847
}

src/Query/Builder.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
use MongoDB\BSON\UTCDateTime;
2424
use MongoDB\Builder\Stage\FluentFactoryTrait;
2525
use MongoDB\Driver\Cursor;
26+
use MongoDB\Laravel\Internal\FindAndModifyCommandSubscriber;
27+
use MongoDB\Operation\FindOneAndUpdate;
2628
use Override;
2729
use RuntimeException;
2830

@@ -725,6 +727,41 @@ public function update(array $values, array $options = [])
725727
return $this->performUpdate($values, $options);
726728
}
727729

730+
/**
731+
* @internal while not stabilized
732+
*
733+
* @return array{inserted:bool, document:array}
734+
*/
735+
public function firstOrInsert(array $values, array $options = [])
736+
{
737+
$options = $this->inheritConnectionOptions($options);
738+
$wheres = $this->compileWheres();
739+
740+
$listener = new FindAndModifyCommandSubscriber();
741+
$this->collection->getManager()->addSubscriber($listener);
742+
743+
try {
744+
$document = $this->collection->findOneAndUpdate(
745+
$wheres,
746+
// Before MongoDB 5.0, $setOnInsert requires a non-empty document.
747+
// This should not be an issue as $values includes the query filter.
748+
['$setOnInsert' => (object) $values],
749+
[
750+
'upsert' => true,
751+
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
752+
'typeMap' => ['root' => 'array', 'document' => 'array'],
753+
] + $options,
754+
);
755+
} finally {
756+
$this->collection->getManager()->removeSubscriber($listener);
757+
}
758+
759+
return [
760+
'inserted' => $listener->created,
761+
'document' => $document,
762+
];
763+
}
764+
728765
/** @inheritdoc */
729766
public function increment($column, $amount = 1, array $extra = [], array $options = [])
730767
{

tests/ModelTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,6 +1117,11 @@ public function testUpdateOrCreate(array $criteria)
11171117
Carbon::setTestNow('2010-01-01');
11181118
$createdAt = Carbon::now()->getTimestamp();
11191119

1120+
$eventUsers = [];
1121+
User::created(function (User $user) use ($eventUsers) {
1122+
$eventUsers[] = $user;
1123+
});
1124+
11201125
// Create
11211126
$user = User::updateOrCreate(
11221127
$criteria,
@@ -1127,6 +1132,8 @@ public function testUpdateOrCreate(array $criteria)
11271132
$this->assertEquals(new DateTime('1987-05-28'), $user->birthday);
11281133
$this->assertEquals($createdAt, $user->created_at->getTimestamp());
11291134
$this->assertEquals($createdAt, $user->updated_at->getTimestamp());
1135+
$this->assertCount(1, $eventUsers);
1136+
$this->assertSame($user, $eventUsers[0]);
11301137

11311138
Carbon::setTestNow('2010-02-01');
11321139
$updatedAt = Carbon::now()->getTimestamp();

0 commit comments

Comments
 (0)