【发布时间】:2021-12-08 08:04:45
【问题描述】:
当我尝试在 laravel 中删除项目时,我收到了这条消息
SQLSTATE[23000]:完整性约束违规:1451 无法删除或更新父行:外键约束失败(larblog.comments,CONSTRAINT comments_article_id_foreign FOREIGN KEY (article_id) REFERENCES articles (id)) (SQL: 从articles 中删除id = 2)
这是我的删除功能
public function DeleteArticle($id){
$article = Article::find($id);
$article->delete();
return redirect("article");
}
这个创建文章表代码
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticle extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
这会创建 cmets 表代码
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateComments extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->text('comment');
$table->timestamps();
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
我尝试使用此解决方案,但没有奏效
$table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')-
>onDelete('cascade');
【问题讨论】:
-
你把这段代码放在哪里了? $table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')->onDelete('cascade');
-
public function up() { Schema::create('cmets', function (Blueprint $table) { $table->increments('id'); $table->text('comment' ); $table->timestamps(); $table->integer('article_id')->unsigned(); $table->foreign('article_id')->references('id')->on('articles ')->onUpdate('cascade')->onDelete('cascade'); }); }
-
您引用的外键必须是
bigInteger或unsignedBigInteger,如$table->unsignedBigInteger('article_id');中所述,如laravel.com/docs/8.x/migrations#foreign-key-constraints 中所述