laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Relation::upsertMany() method #2473

Closed tarraq closed 3 years ago

tarraq commented 3 years ago

In my current project I have nightly jobs fetching data from external API's. Occationally there's a hiccup and I need to re-import.

Now I collect lines in a Collection and do $model->orderLines()->saveMany($collection);.

However it would be great to be able to do $model->orderLines()->upsertMany($collection);, making sure I don't get duplicates and also won't have to delete everything from that day already.

Implementation-wise I would guess it would be fairly simple, using existing upsert functionality, injecting the relation ID as a hidden uniqueness key.

mc0de commented 3 years ago

@tarraq this allready exist

public function updateOrCreate(array $attributes, array $values = [])
{
    return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
        $instance->fill($values)->save();
    });
}

just do

Model::updateOrCreate(['id' => $id], $data);