when i tried delete item in laravel i get this message
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (larblog
.comments
, CONSTRAINT comments_article_id_foreign
FOREIGN KEY (article_id
) REFERENCES articles
(id
)) (SQL: delete from articles
where id
= 2)
this my delete function
public function DeleteArticle($id){
$article = Article::find($id);
$article->delete();
return redirect("article");
}
this create articles table code
<?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');
}
}
and this create comments table code
<?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');
}
}
Iam tried to use this solution but did not work
$table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')-
>onDelete('cascade');
CodePudding user response:
as you know your comments depends on articles once a article is delete then comment's relation going to break so either you first delete all comment's of that artical or set foreign key null to all the comment for that article
so that why you need to update your mygration with
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
or
$table->integer('article_id')->unsigned()->nullable();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('set null');