php – 刷新迁移时的外键约束错误 – Laravel
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 刷新迁移时的外键约束错误 – Laravel,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2274字,纯文字阅读大概需要4分钟。
内容图文
![php – 刷新迁移时的外键约束错误 – Laravel](/upload/InfoBanner/zyjiaocheng/759/8baf7f96d5294488b116769d0dec87ee.jpg)
我在Laravel项目中遇到迁移问题.
因为我对Laravel相当新,所以我无法理解.
我想将一个外键添加到现有的表中,这样可行,但是当我刷新迁移时,我收到此错误:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key
constraint fails (SQL: drop table `battles`)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key
constraint fails
这些是我目前的迁移:
表项目
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->string('tags');
$table->string('img');
$table->string('img_tricolor');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('projects');
}
}
表战
class CreateBattlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('battles', function (Blueprint $table) {
$table->increments('id');
$table->string('battle_theme');
$table->boolean('battle_active');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('battles');
}
}
为项目中的战斗添加外键
class AddProjectsBattleIdFk extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('projects', function (Blueprint $table) {
$table->integer('battle_id')->unsigned();
$table->foreign('battle_id')->references('id')->on('battles')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('projects', function (Blueprint $table) {
//
});
}
}
我想这与战斗表有关.
解决方法:
在down方法中,您需要先删除外键:
在CreateProjectsTable中
public function down()
{
Schema::table('projects', function (Blueprint $table) {
$table->dropForeign('projects_user_id_foreign');
});
Schema::drop('projects');
}
在AddProjectsBattleIdFk中
public function down()
{
Schema::table('projects', function (Blueprint $table) {
$table->dropForeign('projects_battle_id_foreign');
$table->dropColumn('battle_id');
});
}
内容总结
以上是互联网集市为您收集整理的php – 刷新迁移时的外键约束错误 – Laravel全部内容,希望文章能够帮你解决php – 刷新迁移时的外键约束错误 – Laravel所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。