Laravel foreign key onDelete('cascade') not working

十年热恋 提交于 2019-11-30 04:50:41

问题


I have a many-to-many relationship between User & Role, with a role_user table. My migrations are setup as so (simplified):

users table:

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('email')->unique();
    });
}

roles table:

public function up()
{
    Schema::create('roles', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
    });
}

role_user table:

public function up()
{
    Schema::create('role_user', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->integer('role_id')->unsigned();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    });
}

So as per the docs, I set my foreign keys to unsigned.

Now, I add a couple of users, and attach some roles - everything works fine. However, when I delete a user (User::destroy(2)) the rows for that user in the role_user table do not get deleted, which is causing redundant rows.

What am I doing wrong?

  • MySQL + InnoDB

EDIT: Grabbing the model and applying ->delete(); also has the same effect.


回答1:


Try setting when trying to create this table. This fix has worked for me.

$table->engine = 'InnoDB';

I have filed a bug under: https://github.com/laravel/framework/issues/8730




回答2:


Check the MySQL config. my.ini may still have default-storage-engine=MYISAM. Set to default-storage-engine=InnoDB and you should avoid the trouble of adding this fix to each migration.




回答3:


even after changing the engine to InnoDB in Config->Database it does not work

and the solution for that is to change the migration

From

Schema::create('users', function (Blueprint $table) { $table->BigIncrements('id');

To

Schema::create('users', function (Blueprint $table) { $table->increments('id');




回答4:


It is established by Jake's answer that you have set default engine to InnoDB

$table->engine = 'InnoDB';

Instead of doing it in each migration file, You can do so in config/database.php

'mysql' => [
        'driver' => 'mysql',
        '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' => '',
        'strict' => false,
        'engine' => 'InnoDB',
    ],


来源:https://stackoverflow.com/questions/24897300/laravel-foreign-key-ondeletecascade-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!