Laravel $touch 用于更新 updated_at
Laravel $touch for updating updated_at
我对 Laravel 中的 $touch
有疑问。我的理解是,$touch
可用于更新模型或关系而不更新任何其他列。但我正在尝试的是,我需要更新用户 table,无论其他用户发生什么变化 table。
它可以被创建、更新或删除。在我的例子中,$touch
不处理删除关系。
//touch
protected $touches = ['somerelation'];
//relationship
public function somerelation(){
return $this->belongsTo('someModel', 'key_id');
}
public setSomeRelationAttribute(){
$this->someRelation()->delete();
}
这是我试过的。 updated_at 在用户中可以正常创建和更新。但不能删除。
是因为触摸只适用于添加和更新吗?
我通过检查 DB 值来确定,touch 在所有关系中都不适用于删除。
我需要确保我的发现是真实的,触摸不适用于删除
如果您在现有模型上调用 touch()
,例如:
$post = Post::find(1);
$post->touch(); // this updates just this model
因此删除无法对您要删除的行起作用。
但在父模型上它确实有效,例如你有 post 评论,在评论模型中添加:
protected $touches = [ 'post' ];
public function post()
{
return $this->belongsTo(Post::class);
}
即使您删除评论,也会更新 Post。 Here 是删除方法的实现,特别是将触及父模型的行。
-- 编辑
改善您与其中之一的关系:
return $this->belongsTo('App\User');
// or
return $this->belongsTo(User::class);
将更新 $touch 中的 delete() method in Eloquent Model 个关系。
如果它调用 delete() in query-builder ,它不会触及 $touch 中的关系。
我对 Laravel 中的 $touch
有疑问。我的理解是,$touch
可用于更新模型或关系而不更新任何其他列。但我正在尝试的是,我需要更新用户 table,无论其他用户发生什么变化 table。
它可以被创建、更新或删除。在我的例子中,$touch
不处理删除关系。
//touch
protected $touches = ['somerelation'];
//relationship
public function somerelation(){
return $this->belongsTo('someModel', 'key_id');
}
public setSomeRelationAttribute(){
$this->someRelation()->delete();
}
这是我试过的。 updated_at 在用户中可以正常创建和更新。但不能删除。
是因为触摸只适用于添加和更新吗?
我通过检查 DB 值来确定,touch 在所有关系中都不适用于删除。
我需要确保我的发现是真实的,触摸不适用于删除
如果您在现有模型上调用 touch()
,例如:
$post = Post::find(1);
$post->touch(); // this updates just this model
因此删除无法对您要删除的行起作用。
但在父模型上它确实有效,例如你有 post 评论,在评论模型中添加:
protected $touches = [ 'post' ];
public function post()
{
return $this->belongsTo(Post::class);
}
即使您删除评论,也会更新 Post。 Here 是删除方法的实现,特别是将触及父模型的行。
-- 编辑
改善您与其中之一的关系:
return $this->belongsTo('App\User');
// or
return $this->belongsTo(User::class);
将更新 $touch 中的 delete() method in Eloquent Model 个关系。
如果它调用 delete() in query-builder ,它不会触及 $touch 中的关系。