您好,我正在尝试在迁移中定义关系我正在使用删除限制来防止在孩子存在时删除父记录。但它不起作用。例如,我有这个具有版本(子版本(的事件表(父级(。我在版本表中使用event_id 与onDelete('restrict')
并在我的版本表中event_id..它应该限制我从事件表中删除,因为长记录在版本表中有子记录,对吗?但它不是..
以下是两个表的迁移
事件(父级(
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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 IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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');
}
}
根据这个线程:
如果您使用的是 SoftDeletes 特征,则调用 delete(( 模型上的方法只会更新模型中的deleted_at字段 数据库,并且不会触发 onDelete 约束,给定 它是在数据库级别触发的,即当 DELETE 查询 执行。
因此,请确保使用DELETE
不要SoftDeletes
否则您可以手动添加约束。
我看到您的外键定义中缺少的一件事是在其上添加索引,这是对外键的要求,这可能是您的原因。
尝试更改
$table->integer('event_id')->unsigned();
自
$table->integer('event_id')->unsigned()->index();
此外,您可以直接在列定义之后添加外键定义,而无需将其放在不同的Schema::table()
块中。