laravel save\update 方法不更新updated

编程入门 行业动态 更新时间:2024-10-23 17:31:42

laravel   save\update <a href=https://www.elefans.com/category/jswz/34/1771314.html style=方法不更新updated"/>

laravel save\update 方法不更新updated

场景:

      小型论坛,在帖子的表中维持一个最后一个更新的用户  

      如果上次评论的用户的和现在这个评论的用户是同一个人 则不会更新updated_at 字段

解决:

       先说怎么解决 

$last_user_id = $event->comment->user_id;
$discussion_id = $event->comment->discussion_id;
$updated_at = date('Y-m-d H:i:s');
Discuss::where(['id' => $discussion_id])->update(compact('last_user_id','updated_at'));

解析:

Illuminate\Database\Eloquent\Model #527行

     update函数内部调用了save   save 调用了performUpdate  

/**
 * Perform a model update operation.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return bool
 */
protected function performUpdate(Builder $query)
{// If the updating event returns false, we will cancel the update operation so
    // developers can hook Validation systems into their models and cancel this
    // operation if the model does not pass validation. Otherwise, we update.
    if ($this->fireModelEvent('updating') === false) {return false;}// First we need to create a fresh query instance and touch the creation and
    // update timestamp on the model which are maintained by us for developer
    // convenience. Then we will just continue saving the model instances.
    if ($this->usesTimestamps()) {$this->updateTimestamps();}// Once we have run the update operation, we will fire the "updated" event for
    // this model instance. This will allow developers to hook into these after
    // models are updated, giving them a chance to do any special processing.
    $dirty = $this->getDirty();if (count($dirty) > 0) {$this->setKeysForSaveQuery($query)->update($dirty);$this->fireModelEvent('updated', false);$this->syncChanges();}return true;
}
/**
 * Update the creation and update timestamps.
 *
 * @return void
 */
protected function updateTimestamps()
{$time = $this->freshTimestamp();if (! is_null(static::UPDATED_AT) && ! $this->isDirty(static::UPDATED_AT)) {$this->setUpdatedAt($time);}if (! $this->exists && ! $this->isDirty(static::CREATED_AT)) {$this->setCreatedAt($time);}
}
/**
 * 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());
}

更多推荐

laravel save\update 方法不更新updated

本文发布于:2024-02-17 04:01:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1692566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   save   laravel   updated   update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!