我正在尝试在 MySQL 数据库中设置表,并且目前正在使用 Laravel 5.8 创建迁移文件。当我运行新迁移时
php artisan migrate
所有迁移都顺利进行,我的外键已正确添加到我的表中
但是当我想更新我的数据库时
php artisan migrate:refresh
我遇到了这个错误
Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists
services
)
到目前为止我已经尝试过:
将外键拆分到不同的迁移文件中,以便它们位于没有外键的表之后
Visual Studio 代码中的文件架构
在我的 up() 函数中的每个外键上添加 ->onDelete('cascade') (代码如下)
我的服务迁移文件
class CreateServicesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('services', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('price');
$table->boolean('multiple_times');
$table->boolean('location');
$table->integer('animal_type_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('services');
}
}
我的AnimalType外键
class ForeignKeyAnimalTypeServices extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('services', function($table){
$table->foreign('animal_type_id')->references('id')->on('animal_types')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('services', function(Blueprint $table){
$table->dropForeign(['animal_type_id']);
});
}
}
我的服务模型
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'name', 'description', 'price', 'multiple_times', 'location'
];
public function animalType()
{
return $this->belongsTo('App\AnimalType');
}
}
虽然我的迁移已创建,但如果需要(或为我的表播种),我无法刷新我的迁移。我希望能够刷新我的文件而不会出现此错误。 我对编程还很陌生,如果缺少信息,我深表歉意。
最佳答案
迁移中类ForeignKeyAnimalTypeServices
尝试:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::table('services', function(Blueprint $table){
$table->dropForeign(['animal_type_id']);
});
Schema::dropIfExists('services');
Schema::enableForeignKeyConstraints();
}
关于mysql - Laravel 5.8/Mysql : Cannot delete or update a parent row a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743271/