Add “ON DELETE CASCADE” to existing column in Laravel

前端 未结 7 1629
借酒劲吻你
借酒劲吻你 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:02

    Use the unsigned function to user_id in the present migration:

    $table->interger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('table_name')->onDelete('cascade');
    
    0 讨论(0)
  • 2021-02-05 00:04
    $table->integer('user_id')->unsigned();    
    $table->foreign('user_id')
          ->references('id')->on('users')
          ->onDelete('cascade');
    

    I am assuming you used Illuminate\Database\Schema\Blueprint::primary() to create users.id. If that is the case, then users.id will be unsigned. Therefore your foreign key column user_id must also be unsigned.

    0 讨论(0)
  • 2021-02-05 00:06

    Drop foreign key first. Thanks to Razor for this tip

    $table->dropForeign('answers_user_id_foreign');
    $table->foreign('user_id')
    ->references('id')->on('users')
    ->onDelete('cascade');
    
    0 讨论(0)
  • 2021-02-05 00:07
    $table->foreign('user_id')
          ->references('id')->on('users')
          ->onDelete('cascade');
    
    0 讨论(0)
  • 2021-02-05 00:10

    In my case, i'll need to put the col name in an array else that will be an error.

    Schema::table('transactions', function (Blueprint $table) {
        $table->dropForeign(['transactions_order_id_foreign']);
        $table->foreign('order_id')
            ->references('id')->on('orders')
            ->onDelete('cascade')
            ->change();
    });
    

    mysql 5.7 ver

    0 讨论(0)
  • 2021-02-05 00:15

    Thanks for question answer. Help me get to this working code in L5.1 :

    public function up()
    {
        Schema::table('transactions', function (Blueprint $table) {
            $table->dropForeign('transactions_order_id_foreign');
            $table->foreign('order_id')
                ->references('id')->on('orders')
                ->onDelete('cascade')
                ->change();
        });
    
        Schema::table('orders', function (Blueprint $table) {
            $table->dropForeign('orders_user_id_foreign');
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade')
                ->change();
        });
    }
    
    0 讨论(0)
提交回复
热议问题