onDelete Cascade两面

时间:2018-03-14 11:31:10

标签: laravel laravel-5

我使用Laravel Framework,我有多个连接表,当从operations表中删除相关事务时,我成功地从transactions表中删除了一个操作,但我无法&#39 ;让它在对面工作,因为它在迁移时以及向operations表添加新行时都会抛出错误。

Schema::create('operations', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('car_id')->unsigned();
            $table->string('operation');
            $table->integer('transaction')->unsigned();
            $table->timestamps();

        });

        Schema::table('operations', function($table) {
            $table->foreign('car_id')->references('id')->on('cars')->onDelete('cascade');
            $table->foreign('transaction')->references('id')->on('transactions')->onDelete('cascade');
        });

我需要的是删除相关操作时删除交易:

Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->string('status')->index();
            $table->date('date')->index();
            $table->string('user_added');
            $table->string('note')->nullable();
            $table->timestamps();
        });

    Schema::table('transactions', function($table) {
        $table->foreign('id')->references('transaction')->on('operations')->onDelete('cascade');
    });

有没有办法实现这个目标?

现在它在迁移时抛出错误:

  

SQLSTATE [HY000]:常规错误:1215无法添加外键   约束(SQL:alter table transactions添加约束   transactions_id_foreign外键(i d)引用   关于删除级联的operationstransaction

这是正常的,因为operations表按顺序排在transactions之后,即使我将代码的第二部分放在operations表中,当我开始插入时它会抛出类似的错误行到表。

我很感激引导我找到解决方案。

1 个答案:

答案 0 :(得分:0)

看起来你把你的主键添加为foreignkey

Schema::table('transactions', function($table) {
        $table->foreign('id')->references('transaction')->on('operations')->onDelete('cascade');

请在事务表“operations_id”上添加1列,并像这样更改您的架构

Schema::table('transactions', function($table) {
$table->foreign('operations_id')->references('id')->on('operations')->onDelete('cascade');