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

how can i create an initial version for an already existing model entry? #99

Open
iateadonut opened this issue Mar 22, 2023 · 3 comments

Comments

@iateadonut
Copy link
Contributor

The package only creates a version on update, and that version is equal to the current values in the database.

How can I create a version without updating so that if I'm adding this package to an already existing application, I can keep the current entries as versions?

Something like $model->createCurrentVersion().

@nonoesp
Copy link
Collaborator

nonoesp commented Mar 22, 2023

Hi, @iateadonut!

That feature doesn't exist at the moment.

It could be implemented — maybe $mode->createVersion(), as you said — as a public method of the VersionableTrait.

I'm open to pull requests for this, but I have limited bandwidth to maintain this package.

A quick-and-dirty solution would be making a minimal change to one of the versionable fields in your models and saving to force the package to save that as the first version.

Kindly,

Nono

@iateadonut
Copy link
Contributor Author

iateadonut commented Mar 22, 2023

hi, thanks for responding so quickly.

i wrote these functions in an extended trait - take a quick look and let me know if you see any problems and if you'd like me to make a PR for this:

public static function initializeVersionOnAllRows()
{
    foreach (self::all() as $obj) {
        $obj->createInitialVersion();
    }
    return true;
}

/**
 * Save a new version.
 * @return void
 */
public function createInitialVersion()
{
    if(true === $this->versions->isEmpty()) {

        $class                     = $this->getVersionClass();
        $version                   = new $class();
        $version->versionable_id   = $this->getKey();
        $version->versionable_type = method_exists($this, 'getMorphClass') ? $this->getMorphClass() : get_class($this);
        $version->user_id          = $this->getAuthUserId();
        
        $versionedHiddenFields = $this->versionedHiddenFields ?? [];
        $this->makeVisible($versionedHiddenFields);
        $version->model_data       = serialize($this->attributesToArray());
        $this->makeHidden($versionedHiddenFields);

        if (!empty( $this->reason )) {
            $version->reason = $this->reason;
        }

        $version->save();
    }
}

@iateadonut
Copy link
Contributor Author

created this pull request: #100

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