1
0

More than 5 years have passed since last update.

中間テーブルつくってみた

Last updated at Posted at 2019-04-05

中間テーブル教えてもらったからメモ。

環境

Laravel
mysql

テーブル

・profilesテーブル
1:1のデータ

・businesstypesテーブル
1:nのデータ

モデル

・profileモデル

・businesstypesモデル

経緯

・profilesテーブルにフォーム情報送信
・今までは1:1のリレーションで動いていた
・フォーム情報の追加作業する
・追加情報の持っている値が文字列ではなく、配列だった
・1:nのリレーションが必要
・中間テーブルつくる

必要な知識

関係 備考
1:1 hasOne belongsTo
1:N hasMany belongsTo
N:N belongsToMany belongsToMany 中間テーブル必要

やったこと

1.businesstype_profileテーブル作成
2.profileモデルに追記
3.profileコントローラに追記

1.businesstype_profileテーブル作成

Schema::create('businesstype_profile', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('profile_id')->unsigned()->index('profile_id')->comment('プロフィールID');
            $table->integer('businesstype_id')->unsigned()->index('businesstype_id')->comment('業種ID');
            $table->timestamps();
        });

※これが中間テーブルになる
カラム
businesstype_profile_id
profile_id
bisinesstype_id
created_at
updated_at

2.profileモデルに追記

class Profile extends Model
{
    public function businesstype_profile()
    {
        return $this->belongsToMany('App\Models\Businesstype', 'businesstype_profile', 
'profile_id', 'businesstype_id')->orderBy('sort')->withTimestamps();
    }
}

・第1引数では最終的な接続先モデルを指定する
・第2引数では中間テーブル名を指定する
・第3引数では接続元モデルIDを示す中間テーブル内のカラムを指定する
・第4引数では接続先モデルIDを示す中間テーブル内のカラムを指定する

3.profileコントローラに追記

$profile->businesstype_profile()->sync([1, 2]);

更新したプロフィールに、businesstype_profileテーブルのID1とID2を関連付け

ID1 → businesstype_idに1が入る

ID2 → businesstype_idに2が入る

ここに変数入れれば欲しい値渡せる

おまけ

sync()じゃなくて、attach()でもいける。

$profile->businesstype_profile()->attach(4);

attach(4)はbusinesstype_profile関数の第4引数(relatedPivotKey)をみてる

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