0
0

More than 1 year has passed since last update.

【Laravel】中間テーブルのcreated_atだけに値を入れる方法

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

前提

中間テーブルのidやcreated_atに値が入らない状態で、updated_atには値を入れたくない(カラムが存在しないため)とき

解決法

各モデルでリレーションを定義するとき、withPivotで渡したいカラムを入れる。
これでcreated_atがちゃんと保存されるようになる。


# group model
public function userGroups(): BelongsToMany
{
    return $this->belongsToMany(UserGroup::class)
                ->withPivot('id', 'group_id', 'user_id', 'user_group_id', 'created_at');
}

# user model
public function userGroups(): BelongsToMany
{
    return $this->belongsToMany(UserGroup::class)
                ->withPivot('id', 'user_group_id', 'group_id', 'user_id', 'created_at');
}

# user-group model
public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class)->withPivot('id', 'group_id', 'user_id', 'user_group_id');
}

public function groups(): BelongsToMany
{
    return $this->belongsToMany(Group::class)->withPivot('id', 'group_id', 'user_id', 'user_group_id');
}

ちなみに

created_at updated_at両方とも値を持たせたい場合は下記でオッケー。

return $this->belongsToMany(User::class)->withTimestamps();

参考

0
0
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
0
0