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

Allow to define metadata when creating a new document #11

Merged
merged 2 commits into from
Mar 15, 2021
Merged

Allow to define metadata when creating a new document #11

merged 2 commits into from
Mar 15, 2021

Conversation

matthenning
Copy link

In certain use cases we need to define _id when creating a new document.
The newInstance method already allows to pass $metadata as an optional second parameter.
By adding this optional parameter to the create method, we can allow the user to define _id as a metadata field.

Model::create([
  'name' => 'something',
], [
  '_id' => 'my-id-123'
]

@Radiergummi
Copy link
Member

Hey @matthenning, thanks for opening this PR! I'm still thinking about whether making metadata part of the public API is the best solution to this problem: _id is the only metadata field that actually makes sense to be settable.
What do you think of the following:

Model::create([
    'name' => 'something',
], 'my-id-123');

@matthenning
Copy link
Author

That's a valid concern, index and type are already covered via model properties anyway, so no need to expose them via the create method.
How about this version of the create method then?
Would that work for you? In that case I'll go ahead and update the PR.

/**
 * Save a new model and return the instance.
 *
 * @param array $attributes
 * @param string|null $id
 * @return static
 * @psalm-suppress LessSpecificReturnStatement
 */
public static function create(array $attributes, string $id = null): self
{
    $metadata = [];
    if (!is_null($id)) {
        $metadata['_id'] = $id;
    }

    return tap(
        (new static())->newInstance($attributes, $metadata),
        static function ($instance) {
            $instance->save();
        }
    );
}

@Radiergummi
Copy link
Member

Looks fine, just make sure to make the ID parameter type a nullable string:

public static function create(array $attributes, ?string $id = null): self

@Radiergummi Radiergummi merged commit 181d11d into matchory:master Mar 15, 2021
@Radiergummi
Copy link
Member

Thank you for contributing! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants