Add “ON DELETE CASCADE” to existing column in Laravel

前端 未结 7 1633
借酒劲吻你
借酒劲吻你 2021-02-04 23:52

I have user_id fk column in my table

$table->foreign(\'user_id\')->references(\'id\')->on(\'users\');

I should add on cascade

7条回答
  •  悲&欢浪女
    2021-02-05 00:20

    Laravel schema builder can't modify columns at the current state, so you will use raw queries. You will have to drop and recreate the constraint:

    PostgreSQL

    function up()
    {
        DB::statement('alter table answers drop constraint answers_user_id_foreign,
                       add constraint answers_user_id_foreign
                       foreign key (user_id)
                       references users(id)
                       on delete cascade;'
        );
    }
    function down()
    {
        DB::statement('alter table answers drop constraint answers_user_id_foreign,
                       add constraint answers_user_id_foreign
                       foreign key (user_id)
                       references users(id);'
        );
    }
    

    MySQL

    function up()
    {
        DB::statement('alter table answers drop FOREIGN KEY answers_user_id_foreign;');
        DB::statement('alter table answers add constraint answers_user_id_foreign
                       foreign key (user_id)
                       references users(id)
                       on delete cascade;'
        );
    }
    function down()
    {
        DB::statement('alter table answers drop FOREIGN KEY answers_user_id_foreign;');
        DB::statement('alter table answers add constraint answers_user_id_foreign
                       foreign key (user_id)
                       references users(id);'
        );
    }
    

提交回复
热议问题