简体   繁体   中英

Laravel log revisions for many-to-many relationships

I'm a completely new Laravel developer and I'm using the VentureCraft Revisionable library to record model revisions. I need to record revisions for a many-to-many model and it's my understanding that Revisionable does not support this. I've looked at other libraries and they don't seem to either. Is there a way that I can do this? Ie log changes to pivot tables that there are no model classes for?

Sorry for the broad question but I'm stuck and don't really know where to go with this. Any hints or helpful documentation would be much appreciated.

I'd like to use the Revisionable library but really I just need to add a record to the revisions table with the data in the respective pivot table(s) that changed and I have no idea of how to go about doing this. Thanks in advance.

While there is no native way to currently do this, there are a couple options. What I do on certain models that I needed to attach ModelB's saves to ModelA (or whatever scenario) is made a global function in class (or use in helpers.php) to do this:

/**
 * Creates a revision record.
 *
 * @param object $obj
 * @param string $key
 * @param mixed $old
 * @param mixed $new
 *
 * @return bool
 */
public static function createRevisionRecord($obj, $key, $old = null, $new = null)
{
    if (gettype($obj) != 'object') {
        return false;
    }
    $revisions = [
        [
            'revisionable_type' => get_class($obj),
            'revisionable_id' => $obj->getKey(),
            'key' => $key,
            'old_value' => $old,
            'new_value' => $new,
            'user_id' => vms_user('id'),
            'created_at' => new \DateTime(),
            'updated_at' => new \DateTime(),
        ]
    ];
    $revision = new \Venturecraft\Revisionable\Revision;
    \DB::table($revision->getTable())->insert($revisions);
    return true;
}

Then later just call MyHelperClass::createRevisionRecord() from my save() hook.

public function save(array $options = [])
{
    // $old = $this->getOriginal('key');
    // $new = $this->key;
    // Let's say this is linked to \App\SomethingElse via 'something_id'

    MyHelperClass::createRevisionRecord(\App\SomethingElse::find($this->something_id), 'custom_field', $old, $new);

    // Do actual save.
    return parent::save($options);
}

It's not the most elegant way, but it was my first working hacky option.

That being said.. There will be built-in functionality for this in Revisionable v2.0+ which is being worked on!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM