LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】migrate時のエラー解決集

Last updated at Posted at 2022-06-24

laravel開発でphp artisan migrateを実行した際のエラーまとめ

default値を設定できない型(BLOG型、TEXT型、GEOMETRY型、JSON型)

.エラー内容
SQLSTATE[42000]: Syntax error or access violation: 1101 BLOB, TEXT, GEOMETRY or JSON column 'content' can't have a default value (SQL: create table `blog_posts` (`id` bigint unsigned not null auto_increment primary key, `created_at` timestamp null, `updated_at` timestamp null, `title` varchar(255) not null default '', `content` text not null default '') default character set utf8mb4 collate 'utf8mb4_general_ci')

マイグレーションファイルのtext型のcontentにデフォルト値を設定していたのが原因

create_blog_posts_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blog_posts', function (Blueprint $table) {
            $table->id();
            $table->timestamps();

            $table->string('title')->default('');
            // $table->text('content')->default('');  <- error
            $table->text('content');
        });
    }

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

外部キー制約で型に互換性がない

.エラー内容
  SQLSTATE[HY000]: General error: 3780 Referencing column 'author_id' and referenced column 'id' in foreign key constraint 'profiles_author_id_foreign' are incompatible. (SQL: alter table `profiles` add constraint `profiles_author_id_foreign` foreign key (`author_id`) references `authors` (`id`))
create_authors_table.php
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }
create_profiles_table.php
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->id();
            $table->timestamps();

            // $table->unsignedInteger('author_id')->unique(); <- error
            $table->unsignedBigInteger('author_id')->unique();
            $table->foreign('author_id')->references('id')->on('authors');
        });
    }

【authorのidとprofileのauthor_idを制約時にエラー】
author id : bigint(unsigned)
profile author_id : int(unsigned)
であり型に互換性がないためエラーが発生

profile author_idをunsignedBigInteger('author_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