📚

【フォロー機能】Migration followsテーブル作成

2021/08/08に公開
php artisan make:model follow -m

エラー

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `follows` add constraint `follows_following_id_foreign` foreign key (`following_id`) references `users` (`id`))

unsignedBigIntegerに修正
解決
https://qiita.com/kitakrazy/items/6a3e1936da727dbd92b3

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'follows' already exists (SQL: create table `follows` (`id` bigint unsigned not null auto_increment primary key, `following_id` bigint unsigned null, `followed_id` bigint unsigned null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

解決
https://qiita.com/namizatork/items/f8c414fec4e6b76b3ed4

上記で以下

Migration not found: 2021_08_05_234714_create_music_files_user_table
Doctrine\DBAL\Schema\SchemaException  : There is no column with name 'music_files' on table 'music_files'.

ロールバックが必要なないmigrationファイルは削除してしまう
https://nebikatsu.com/7570.html/

成功

src/database/migrations/2021_08_08_163306_create_follows_table.php

<?php

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

class CreateFollowsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('follows', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('following_id')->nullable();
            $table->unsignedBigInteger('followed_id')->nullable();
            $table->timestamps();

            $table->foreign('following_id')
                  ->references('id')->on('users')
                  ->OnDelete('cascade');
            $table->foreign('followed_id')
                  ->references('id')->on('users')
                  ->OnDelete('cascade');

                  $table->unique(['following_id', 'followed_id']);
        });
    }

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

ref
https://qiita.com/wrbss/items/7245103a5fef88cbdde9

Discussion

ログインするとコメントできます