取自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;
}