LoginSignup
0
1

More than 5 years have passed since last update.

Laravel5.5で外部キー制約の親を消したら子も消えるやつ(備忘録)

Posted at

投稿テーブル作成(親の方)

php artisan make:model Post --migrationやってモデルとマイグレーションファイル作る。

続いて、マイグレーションファイルを以下の様にいじる。

migrationファイル

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

投稿に紐づくコメントテーブル作成(子供達)

php artisan make:model Comment --migrationやってモデルとマイグレーションファイル作る。

続いて、マイグレーションファイルを以下の様にいじる。

migrationファイル

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->string('body');
            $table->timestamps();
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

onDelete('cascade')ってのが参照してる親のIDが消滅したら自分も消滅しまっせって記述。

モデルいじってコントローラーにて関係性を使いやすく。

$post->comments的にアクセルできる様にするやつ。

Postモデル

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
  // protected $fillableで挿入するカラムを指定すると安全にcreateできる様になる。
  protected $fillable = ['title', 'body'];

  public function comments() {
    return $this->hasMany('App\Comment');
  }
}

Commentモデル
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    //
  protected $fillable = ['body'];

  public function post() {
    return $this->belongsTo('App\Post');
  }
}

hasManyやらbelongsToで1対多の関係性を表現している。

捕捉

多対多の関係性を作るときは中間テーブル必要。

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