LoginSignup
8
3

More than 1 year has passed since last update.

Laravelの中間テーブルにcreated_atだけ自動的に渡す方法

Posted at

確認したバージョン

Laravel 8

どういうこと?

以下のようなクラスがあったとします。

class Foo extends Model
{
    public function bars() {
        $this->belongsToMany(Bar::class);
    }
}

このとき、barsの中間テーブルとなるfoo_barに作成日時を勝手にinsertしてほしいといった事があるかと思います。

自動でやってくれないかな?と思って、何も考えずにsyncやattachをすると、created_atカラムはnot null制約があるから違反してるぞ!と怒られちゃいます。

まず思いつくのは以下です。正直先程までこの方法を使っていました。

$foo->bars()->attach($id, ['created_at' => Carbon::now()]);

とか

$foo->bars()->syncWithPivotValues($ids, ['created_at' => Carbon::now()]);

しかしながらもっと簡単な方法がありましたので紹介します。

簡単な方法

withPivotでcreated_atカラムを指定する方法です。

class Foo extends Model
{
    public function bars() {
        $this->belongsToMany(Bar::class)->withPivot('created_at');
    }
}

これだけで勝手に中間テーブルのcreated_atカラムに日時が入っちゃうんですね〜。

詳しい実装内容に関しては以下のソースを確認してください。
https://github.com/laravel/framework/blob/44e3be7edf9c5b17e2d69e827ab144cb44fcf10d/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php#L383-L409

実は、これ以外にwithTimestamps()というのもあるのですがこれはupdated_atもある前提になってしまうので、今回の目的とは違っていたので使えませんでした・・・。

8
3
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
8
3