0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】多対多のリレーション(紐づけの操作について)

Last updated at Posted at 2019-12-25

多対多の紐づけ操作のメソッド、attach(),detach()についてのメモです。
前回は多対多の関係の構造と定義についてメモしています。
多対多のリレーション(構造、定義)

Laravelでは多対多の関係における紐づけはattach(),detach()などのヘルパメソッドが利用できる。

attach()
役割の付与=中間テーブルへのデータの追加(insertの操作)


public function addFavorite(Int $user_id)
{
    return $this->favorites()->attach($user_id);
}

detach()
役割の削除=中間テーブルへのデータの追加(deleteの操作)


public function rmFavorite(Int $user_id)
{
    return $this->favorites()->detach($user_id);
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?