LoginSignup
1
0

【Laravel】中間テーブルを作成する方法

Posted at

中間テーブルの命名規則

・2つのテーブルをアルファベット順に並べる。(例:circles→students)
・2つのテーブルを単数形にして_でつなげる。(例:circle_student)

中間テーブルの作成方法

①マイグレーションファイルを作成する。
 VSCodeのターミナルまたは、コマンドプロンプトで以下を実行する。

php artisan make:migration create_circle_student_table --create=circle_student

※すべてのcircle_student は任意のテーブル名を入力する。

以下のように表示されればOK。
image.png

②マイグレーションファイルにカラムを設定する。
 database/migrationsフォルダ内のファイルを編集する。

****_**_**_******_create_circle_student_table.php
 public function up()
    {
        Schema::create('_create_circle_student_table', function (Blueprint $table) {
            $table->id();
             $table->foreignId('circle_id')->constrained()->cascadeOnDelete();  // ここを追加
             $table->foreignId('student_id')->constrained()->cascadeOnDelete(); // ここを追加           
            $table->timestamps();
        });
    }

・foreignId('カラム名')->constrained():foreignId()の引数に設定したカラムに外部キーを設定する。
・cascadeOnDelete():circleテーブルやstudentテーブルのidが消された場合に中間テーブルのレコードも自動で削除される。

③マイグレーションを行う。
 VSCodeのターミナルまたはコマンドプロンプトで以下を実行する。

php artisan migrate

以下のように表示されればOK。
image.png

リレーションシップを設定する

両方のモデルにリレーションシップを設定する。
app\Models\circle.php、student.php に以下を記述する。

circle.php
 public function students() {
     return $this->belongsToMany(Student::class)->withTimestamps();
 }  
student.php
 public function circles() {
     return $this->belongsToMany(Circle::class)->withTimestamps();
 }  

・belongsToMany():多対多のリレーションシップを設定できる。
・withTimestamps():タイムスタンプ(created_atカラムとupdated_atカラムの値)が自動的に保存する。
 (中間テーブルはタイムスタンプが自動で保存されないため。)

コントローラを編集する

・中間テーブルにデータを保存する場合はsync()メソッドを使用する。
例:circle_idが1、student_idが3の場合

$circle->students()->sync(3);

中間テーブルは以下のようになる。

ID circle_id student_id
1 1 3

※上記の状態で、student_idを1,2と紐づけた場合、以下のようになる。

$circle->students()->sync([1,2]);

中間テーブルは以下のようになる。

ID circle_id student_id
2 1 1
3 1 2

↑ ID:1のレコードが自動で削除される。

・実際に記述する場合(例)

○○Controller.php
$circle->students()->sync($request->input('student_ids'));

ビューを編集する

コントローラに値を渡したい場合は以下のように記述する。(例)

index.blade.php
<input type="checkbox" name="student_ids[]" value="{{ $student->id }}"

※name属性の[]は、配列で複数の値をコントローラに渡す記述になる。

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