【问题标题】:Laravel log revisions for many-to-many relationships多对多关系的 Laravel 日志修订
【发布时间】:2016-08-23 13:59:39
【问题描述】:

我是一个全新的 Laravel 开发人员,我正在使用 VentureCraft Revisionable 库来记录模型修订。我需要记录多对多模型的修订,我的理解是 Revisionable 不支持这一点。我看过其他图书馆,他们似乎也没有。有没有办法我可以做到这一点? IE。记录对没有模型类的数据透视表的更改?

抱歉,这个问题很笼统,但我被困住了,真的不知道该去哪里。任何提示或有用的文档将不胜感激。

我想使用 Revisionable 库,但实际上我只需要在修订表中添加一条记录,其中相应数据透视表中的数据发生了变化,我不知道如何去做.提前致谢。

【问题讨论】:

    标签: php laravel eloquent revisionable


    【解决方案1】:

    虽然目前没有本地方法可以做到这一点,但有几个选择。我在需要将 ModelB 的保存附加到 ModelA(或任何场景)的某些模型上所做的事情是在类中(或在 helpers.php 中使用)中的全局函数来执行此操作:

    /**
     * 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;
    }
    

    然后稍后只需从我的save() 挂钩中调用MyHelperClass::createRevisionRecord()

    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);
    }
    

    这不是最优雅的方式,但它是我第一个工作的 hacky 选项。

    话虽如此.. Revisionable v2.0+ 将为此提供内置功能!

    【讨论】:

    • 谢谢,@Austin。我最终编写了自己的 hacky 解决方案,但我更喜欢你的解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 2018-06-15
    • 2018-01-22
    • 2016-02-26
    • 2016-01-04
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多