首页 文章

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

提问于
浏览
1

我的数据库中有很多关系,在子模型中我有 touches 数组定义如此

protected $touches = ['parent'];

我希望做一些类似于这两个问题所描述的内容:

但是稍有不同,我希望在子模型中发生更改时更新父模型上的布尔列 . 这适用于触摸,但我无法弄清楚如何使用自定义属性来执行此操作 .

我在我的父模型中试过这个但没有用:

public static function boot()
{
    parent::boot();

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

1 回答

  • 1

    根据this thread,似乎 updating() 事件仅在模型为"dirty,"的情况下触发,即具有已更改值的字段,因此需要更新 . 因此,如果父模型上的数据没有更改,则可能是您的代码永远不会被执行 . 我的猜测是,即使触及父级的时间戳,也可以将其从可被视为脏的属性列表中豁免 .

    您可能只需将此代码添加到子模型:

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

    没有测试过这个,但不明白为什么它不应该工作 .

相关问题