- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 Laravel 中,模型具有 belongs to
与另一个的关系,也有<parent>_id
其表中指向 id
的字段 parent 的。当该模型与另一个模型关联时 updated_at
timespamp 自然会更新,就像 <parent>_id
的值一样。字段更改。
父模型,即带有 has many
的模型关系,当它与子模型相关或不再相关时,没有任何字段会发生变化,因此它的 updated_at
时间戳不会改变。
我想要的是父模型和子模型都自动更新它们的 updated_at
每次创建或删除两者之间的关系时都会产生时间戳。实现这一目标的正确方法是什么?
我已经研究过 touches属性,这会导致父级的时间戳在子级被修改时自动更新。但这仅在创建新关系时有效,而在删除旧关系时无效。而且,这将在任何字段更改时更新父级的时间戳,而不仅仅是 <parent>_id
的时间戳。这实际上并不是我想要的。
最佳答案
取自 Laravel Docs .
当一个模型belongsTo
或belongsToMany
另一个模型时,例如属于Post
的Comment
,有时,在更新子模型时更新父模型的时间戳会很有帮助。例如,当更新 Comment
模型时,您可能希望自动“触摸”所属 Post
的 updated_at
时间戳。 Eloquent 使事情变得容易。只需添加一个包含子模型关系名称的 touches
属性即可:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
/**
* All of the relationships to be touched.
*
* @var array
*/
protected $touches = ['post'];
/**
* Get the post that the comment belongs to.
*/
public function post()
{
return $this->belongsTo('App\Post');
} }
现在,当您更新Comment
时,所属的Post
的updated_at
列也会更新,让您更方便了解何时使 Post
模型的缓存失效:
$comment = App\Comment::find(1);
$comment->text = 'Edit to this comment!';
$comment->save();
模型上的删除方法会更新所有者时间戳方法取自 Illuminate\Database\Eloquent\Model.php
要手动更新,您可以运行$this->touchOwners();
public function delete()
{
if (is_null($this->getKeyName())) {
throw new Exception('No primary key defined on model.');
}
// If the model doesn't exist, there is nothing to delete so we'll just return
// immediately and not do anything else. Otherwise, we will continue with a
// deletion process on the model, firing the proper events, and so forth.
if (! $this->exists) {
return;
}
if ($this->fireModelEvent('deleting') === false) {
return false;
}
// Here, we'll touch the owning models, verifying these timestamps get updated
// for the models. This will allow any caching to get broken on the parents
// by the timestamp. Then we will go ahead and delete the model instance.
$this->touchOwners();
$this->performDeleteOnModel();
$this->exists = false;
// Once the model has been deleted, we will fire off the deleted event so that
// the developers may hook into post-delete operations. We will then return
// a boolean true as the delete is presumably successful on the database.
$this->fireModelEvent('deleted', false);
return true;
}
关于laravel - 创建或删除关系时如何自动更新父模型的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888153/
给定一个带有多个 date_time 戳的字符串,我想 提取第一个戳及其前面的文本 候选字符串可以有一个或多个时间戳 后续的 date_time 戳记将被 sep="-" 隔开 后续date_time
是否可以合并从相机拍摄的文本和照片?我想在照片上标记日期和时间,但我在 Google 上找不到任何内容。 最佳答案 使用下面的代码来实现你所需要的。 Bitmap src = Bitm
有没有办法通过 Graph API 戳另一个用户?基于this post ,并使用 Graph Explorer ,我发布到“/USERID/pokes”,我已经授予它(Graph API 应用程序和
我有两个向左浮动的元素。一个是 body 的第一个 child ,另一个是容器的第一个 child ,容器是 body 的第二个 child 。 ...
我是一名优秀的程序员,十分优秀!