mysql Laravel/Lumen not create Foreign Key constraints on migration [duplicate]

x8goxv8g  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(135)

This question already has answers here:

MySQL Creating tables with Foreign Keys giving errno: 150 (20 answers)
Closed last year.
This post was edited and submitted for review 8 hours ago.
I'm working with Laravel8. I have two tables contact_lists and contacts
I contact_lists have many contacts .
Here is my migration code for generation of foreignKey contstraints on contact_lists

public function up()
   {
      Schema::create('contacts', function (Blueprint $table) {
         $table->id();
         $table->unsignedBigInteger('user_id');
         $table->foreignId('contact_list_id')->nullable()->constrained()->onDelete('cascade');
         $table->string('first_name');
         $table->string('last_name');
         $table->string('phone');
         $table->longText('organization')->nullable();
         $table->longText('note')->nullable();
         $table->timestamps();
      });
   }

But I don't know why foreign key is not generating.

pcww981p

pcww981p1#

Laravel use MyISAM as default mysql storage engine. So make sure in config/database/
'engine' => 'InnoDB'

Default:

'mysql' => [
                'driver' => 'mysql',
                'url' => env('DATABASE_URL'),
                'host' => env('DB_HOST', '127.0.0.1'),
                'port' => env('DB_PORT', '3306'),
                'database' => env('DB_DATABASE', 'forge'),
                'username' => env('DB_USERNAME', 'forge'),
                'password' => env('DB_PASSWORD', ''),
                'unix_socket' => env('DB_SOCKET', ''),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => '',
                'prefix_indexes' => true,
                'strict' => true,    
                'engine' => null,
                'options' => extension_loaded('pdo_mysql') ? array_filter([
                    PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
                ]) : [],
            ],

Updated:

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,    
            'engine' => 'InnoDB',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

相关问题