gpt4 book ai didi

php - Laravel 无法删除或更新父行 : a foreign key constraint fails

转载 作者:可可西里 更新时间:2023-11-01 06:28:02 29 4
gpt4 key购买 nike

出于某种原因,用户无法删除已被点赞的帖子,它之前是有效的,但是当我将帖子与喜欢链接时,我一直收到此错误,我什至无法在 Sequel Pro 中删除它,除非我删除首先是与帖子相关的点赞。

错误

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete orupdate 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 whereid = 149)

也许这是我的模式?

帖子架构

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::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 表中删除记录。

一种解决方案是在 likes 迁移文件中使用 onDelete('cascade'):

Schema::create('likes', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

这样,当一个帖子被删除时,所有相关的赞也会被删除。

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

关于php - Laravel 无法删除或更新父行 : a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544109/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com