laravel save\update 方法不更新updated_at 解析

场景:

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

      如果上次评论的用户的和现在这个评论的用户是同一个人 则不会更新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()
    );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值