LoginSignup
1
1

More than 5 years have passed since last update.

[Laravel 5.7] Eloquent リレーションテーブル間で timestamps を連携する方法

Last updated at Posted at 2018-10-29

できること

子のモデルが更新されたタイミングで親のモデルのtimestampsも自動更新する。

参考

公式ドキュメント Eloquent: Relationships > Touching Parent Timestamps
https://laravel.com/docs/5.7/eloquent-relationships#touching-parent-timestamps

2018.12.5 追記

5.7のドキュメントと比較したところ、特に変わったところはないようなので↑のURLを5.7に書き換えました。

方法

belongsTo もしくは belongsMany で親のモデルと紐づいている子のモデルに touches プロパティを設定する。
こうすれば、子の更新タイミングで親のtimestampsも自動更新することが可能。


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $touches = ['post'];

    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

こんな感じで touches プロパティをつけておけば、 Comment が更新されると Post.update_at も同じように更新される。便利。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1