Laravel Migrations onDelete限制不起作用

时间:2018-03-20 08:48:13

标签: php mysql laravel

您好我试图在我的迁移中定义关系 我使用删除限制来防止在孩子出现时删除父记录。但它不起作用。例如,我有这个具有版本(子)的事件表(父)。我在版本表中使用了event_id  使用onDelete('restrict')并在我的版本表中使用event_id 它应该限制我从事件表中删除因为长记录在版本表中有子记录吗?但它不是..

以下是两个表的迁移

事件(父母)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            //master table
            $table->increments('event_id');
            $table->string('name');
            $table->text('full_name');
            $table->text('description');
            $table->tinyInteger('status');
            $table->integer('created_by');
            $table->integer('updated_by');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('events');
    }
}

版本(儿童)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEditionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('editions', function (Blueprint $table) {
            $table->increments('edition_id');
            $table->integer('event_id')->unsigned();
            $table->string('name');
            $table->dateTime('start')->nullable();
            $table->dateTime('end')->nullable();
            $table->enum('stage', ['Archived', 'Cancelled', 'Closed', 'Live', 'On-site', 'Pre-event', 'Sold out'])->nullable()->default('Pre-event');
            $table->tinyInteger('status');
            $table->integer('created_by');
            $table->integer('updated_by');
            $table->timestamps();

        });

        Schema::table('editions', function($table) {

            $table->foreign('event_id')
                ->references('event_id')->on('events')
                ->onDelete('restrict')->onUpdate('restrict');




        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('editions');
    }
}

2 个答案:

答案 0 :(得分:2)

我在外键定义中看到的一件事就是在其上添加一个索引,这是外键的一个要求,它可能是你的问题所在。

尝试更改

ClassCastException

$table->integer('event_id')->unsigned();

此外,您只需在列定义后立即添加外键定义,无需将其放在不同的$table->integer('event_id')->unsigned()->index(); 块中。

答案 1 :(得分:2)

根据thread

  

如果您使用的是SoftDeletes特征,则调用delete()   模型上的方法只会更新你的模型中的deleted_at字段   给定数据库,并且不会触发onDelete约束   它是在数据库级别触发,即DELETE查询时   执行。

因此请确保您使用DELETE而不是SoftDeletes,否则您可以手动添加约束。

相关问题