更新上层时间戳

当模型 belongsTo 另一个模型时,比方说一个 Comment 属于一个 Post ,如果能在子模型被更新时,更新上层的时间戳,这将会很有用。例如,当 Comment 模型更新时,您可能想要能够同时自动更新 Post 的 updated_at 时间戳。 Eloquent 让事情变得很简单。只要在子关联的类里,把关联方法名称加入 touches 属性即可:

class Comment extends Model {
    protected $touches = ["post"];
    public function post()
    {
        return $this->belongsTo("AppPost");
    }
}

现在,当您更新 Comment 时,对应的 Post 会自动更新 updated_at 字段:

$comment = Comment::find(1);
$comment->text = "Edit to this comment!";
$comment->save();
文章导航