讨论数量:
$arr = $model->terms()->sync(array_filter($input['terms']));
if(array_filter($arr)){
$model->touch();
}
原始写法了,看了下代码。laravel 好像不支持更改中间表的自动识别两个主表是否有时间戳字段并更新。
只是在同步的时候,判断分别判断两个主表是否有 touch 并更新。
就是上面的写法可以改为在 term 模型中添加 touchs 属性。 这样中间表更新的时候就可以自动更新了,但是这样的话。 更改 term 表内容的时候,同样会自动更新。 看自己的取舍了。
@superSnail $touches 数组中包含的是自定义的需要被更新的父级模型关联。
protected function finishSave(array $options)
{
$this->fireModelEvent('saved', false);
if ($this->isDirty() && ($options['touch'] ?? true)) {
$this->touchOwners();
}
$this->syncOriginal();
}
Illuminate\Database\Eloquent\Model.php 中 finishSave () 方法。当数据有变,默认进行 touch。
使用可变变量去操作,所以和什么形式无关,只需要保持 $touches 中关联名和模型中定义的关联方法名一致。
推荐文章: