自定义";触摸“;Laravel模型的功能


Custom "touches" functionality for Laravel model

我的数据库中有一个有很多关系,在子模型中,我定义了类似的touches数组

 protected $touches = ['parent'];

我想做一些类似于这两个问题中描述的事情:

  • 使用touch()更新laravel中自定义时间戳字段的时间戳
  • Laravel中的自定义时间戳

但略有不同的是,我希望在子模型发生更改时更新父模型上的布尔列。这适用于触摸,但我不知道如何使用自定义属性。

我在我的父模型中尝试过,但没有成功:

public static function boot()
{
    parent::boot();
    static::updating(function ($table) {
        $table->is_finished = true;
    });
}

根据这个线程,updating()事件似乎只在模型"脏"的情况下触发,即字段的值发生了变化,因此需要更新。因此,如果父模型上的数据没有更改,则可能是您的代码永远不会被执行。我的猜测是,即使父对象上的时间戳被触摸,它也不在可以被视为脏的属性列表中。

相反,您可以将此代码添加到子模型中:

// this is whatever property points to the parent model
public function parent() {
    return $this->belongsTo('App'Parent');
}
// this overrides the update() method in the Eloquent'Model class
public function update($attributes = Array, $options = Array) {
    parent::update($attributes, $options);
    $this->parent->is_finished = true;
    $this->parent->save();
}

尚未对此进行测试,但不明白为什么它不起作用。