出于某种原因,如果帖子已被点赞,则用户无法删除该帖子,它以前可以使用,但是当我将帖子与点赞链接时,我收到此错误,我什至无法在 Sequel Pro 中删除它,除非我删除关联的点赞首先是帖子。
错误
SQLSTATE [23000]:完整性约束违规:1451 无法删除或更新父行:外键约束失败(
eliapi8
likes
,CONSTRAINTlikes_post_id_foreign
(post_id
) REFERENCESposts
(id
)) (SQL: delete fromposts
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);
}
原文由 BARNOWL 发布,翻译遵循 CC BY-SA 4.0 许可协议
是的,这是您的架构。
likes.post_id
的约束将阻止您从posts
表中删除记录。一种解决方案是在
likes
迁移文件中使用onDelete('cascade')
:这样,当一个帖子被删除时,所有相关的喜欢也将被删除。
或者,如果您有从 Post 模型到 Like 模型的关系,您可以在删除帖子本身之前
$post->likes()->delete()
。