updating 和 updated 事件触发描述是否有出入?
Eloquent: 入门,观察器部分 所说,“如果模型已经存在于数据库中并且调用了 save 方法,会触发 updating 和 updated 事件。”与实际情况有点出入,或者描述有点不清晰。实际情况应该是只有调用了模型的save()方法,且模型给定属性已被修改才会触发 updating 和 updated 事件。。相关信息可以看 Eloquent\Model.php 源码 542 行。
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
// If the model already exists in the database we can just update our record // that is already in this database using the current IDs in this "where" // clause to only update this model. Otherwise, we'll just insert them. if ($this->exists) { $saved = $this->isDirty() ? $this->performUpdate($query) : true; }
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
/** * Determine if the model or given attribute(s) have been modified. * 确定模型或给定属性是否已被修改。 * * @param array|string|null $attributes * @return bool */ public function isDirty($attributes = null) { return $this->hasChanges( $this->getDirty(), is_array($attributes) ? $attributes : func_get_args() ); }
对于模型事件触发这一块 文档一直模棱两可 不知阁下能否在评论中详尽补充下
这个问题的关键是 save 方法,因为这个方法在不同的环境下会有不同的效果。如果一个 Model 他还不存在,则调用 save 方法的作用是 insert 一条记录。如果此 Model 已经存在于数据库,则调用 save 方法的效果是 Update 这条存在的记录。
所以文档强调的是:如果你调用 save 方法来更新 Model,那么只有这个 Model 对应的数据存在于数据库中时,才会触发 updating 和 updated 事件(因为不存在的话就是 insert 操作,会触发 creating 和 craeted 事件)。如果你调用 save 方法来保存或更新 Model,那么不管数据记录是否已经存在,都会触发 saving 和 saved 这两个事件。文档表述可能存在问题,但意思是这个意思。