【问题标题】:Custom "touches" functionality for Laravel modelLaravel 模型的自定义“触摸”功能
【发布时间】:2016-09-05 23:33:37
【问题描述】:
我的数据库中有很多关系,在子模型中我有这样定义的 touches 数组
protected $touches = ['parent'];
我希望做类似于这两个问题中描述的事情:
但略有不同,我希望在子模型发生更改时更新父模型上的布尔列。这适用于触摸,但我不知道如何使用自定义属性来代替。
我已经在我的父模型中尝试过,但没有成功:
public static function boot()
{
parent::boot();
static::updating(function ($table) {
$table->is_finished = true;
});
}
【问题讨论】:
标签:
php
mysql
laravel
laravel-5
laravel-5.2
【解决方案1】:
根据this thread,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();
}
尚未对此进行测试,但不明白为什么它不应该工作。