首页 > 解决方案 > 不触及某些字段的时间戳

问题描述

我有几个带有时间戳和active字段的模型,以及我更新它们的代码中的几个部分。我希望能够更新模型,并且仅在更新的模型更改大于活动字段时才触摸时间戳。所以我的代码是

 const leaveUntouched=["active"=>true]
 ...   
 $instance = $model::find($data["id"]);
 $changed = array_diff_assoc($data,$instance->toArray());
 $needTimestampTouch = array_diff_key($changed,self::leaveUntouched);
 if (empty($needTimestampTouch))
   $instance->timestamps = false;
 $instance->fill($data);
 $instance->save();

如果我可以在 BaseModel 本身中定义它,它会更干净。我应该在我的基类中扩展 Eloquent/Model 的填充方法吗?我该怎么做?

标签: eloquent

解决方案


For reference:

I put this in my Baseclass and it works:

protected $preventTouch=['active'];

public function save(array $options = [])
{
    $needsUpdate=array_diff(
        array_keys($this->getDirty()),
        $this->preventTouch
    );
    $this->timestamps = count($needsUpdate) > 0;
    parent::save($options);
}

推荐阅读