mysql – Laravel无法删除或更新父行:外键约束失败

由于某种原因,用户无法删除帖子,如果它已被喜欢,它之前正在工作,但当我将帖子与喜欢的帖子相关时,我一直收到此错误,我甚至无法在Sequel Pro中将其删除,除非我删除相关的相关内容先发帖子.

错误

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails
(eliapi8.likes, CONSTRAINT likes_post_id_foreign FOREIGN KEY
(post_id) REFERENCES posts (id)) (SQL: delete from posts where
id = 149)

Sequel Pro on Mac

也许这是我的架构?

帖子架构

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('body');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
});

喜欢Schema

Schema::create('likes', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('post_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');
    $table->foreign('user_id')->references('id')->on('users');
    $table->softDeletes();
    $table->timestamps();
});

我喜欢和不喜欢的帖子,但用户无法删除已被喜欢的帖子.

PostController.php

public function destroy(Post $post){

    $this->authorize('delete', $post);
    $postl =  Post::with('likes')->whereId($post)->delete();

    if ($post->delete()) {
        if($postl){
             return response()->json(['message' => 'deleted']);
        }  
    };

    return response()->json(['error' => 'something went wrong'], 400);
}
是的,这是你的架构.对likes.post_id的约束将阻止从posts表中删除记录.

一个解决方案可能是在喜欢的迁移文件中使用onDelete(‘cascade’):

Schema::create('likes', function (Blueprint $table) {
    // Some other fields...

    $table->integer('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

这样,当删除帖子时,所有相关的喜欢也将被删除.

或者,如果你有从Post模型到Like模型的关系,你可以在删除帖子之前$post-> likes() – > delete().

https://stackoverflow.com/questions/47544109/laravel-cannot-delete-or-update-a-parent-row-a-foreign-key-constraint-fails

转载注明原文:mysql – Laravel无法删除或更新父行:外键约束失败