php - 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 可以正常使用创建和更新。但不是为了删除。
是不是因为触摸只适用于添加和更新?
通过检查数据库值,我确保在所有关系中都无法删除。
我需要确保我的发现是真实的,触摸不适用于删除
解决方案
例如,如果您正在调用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);
推荐阅读
- arrays - 将更改后的数组重置为其原始值 Swift
- delphi - 如果新目录已经存在,则从旧目录复制自己到新目录中
- javascript - 将我的字符串的一部分与对象数组匹配
- amazon-web-services - 难以将 S3 jsonl 数据中的大型数据帧加载到胶水中以转换为镶木地板:内存约束和工人产卵失败
- c++ - 我在哪里可以找到 d3dcompiler_43.dll 和相应的 lib 文件?
- javascript - 如何从div中获取变量值
- mustache - 访问 mustache 中的变量
- python - 如何注释可以转换为布尔值的参数?
- java - 带有枚举的 CodecConfigurationException
- bash - 一个接一个地运行期望生成的命令