首页 > 解决方案 > Laravel $touch 用于更新 updated_at

问题描述

我对 Laravel 有疑问$touch。我的理解是,$touch可用于更新模型或关系而不更新任何其他列。但我正在尝试的是,我需要更新用户表,无论其他用户相关表中发生什么变化。它可以被创建、更新或删除。就我而言,$touch不使用删除关系。

//touch
protected $touches = ['somerelation'];

//relationship
public function somerelation(){
    return $this->belongsTo('someModel', 'key_id');
}

public setSomeRelationAttribute(){
  $this->someRelation()->delete();
}

这是我尝试过的。用户中的 updated_at 可以正常使用创建和更新。但不是为了删除。

是不是因为触摸只适用于添加和更新?

通过检查数据库值,我确保在所有关系中都无法删除。

我需要确保我的发现是真实的,触摸不适用于删除

标签: phplaravellaravel-5.7

解决方案


例如,如果您正在调用touch()现有模型:

$post = Post::find(1);
$post->touch(); // this updates just this model

因此,删除无法对您要删除的行起作用。

但是在父模型上它确实有效,因此例如您发布了带有评论的帖子,在您添加的评论模型中:

protected $touches = [ 'post' ];

public function post()
{
    return $this->belongsTo(Post::class);
}

即使您删除评论,这也会更新帖子。是删除方法的实现,特别是将触及父模型的行。

- 编辑

改善您与其中之一的关系:

return $this->belongsTo('App\User');

// or

return $this->belongsTo(User::class);

推荐阅读