Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

sql - Laravel foreign key onDelete('cascade') not working

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...