Laravel 无法删除或更新父行:外键约束失败
由于某种原因,如果帖子已被喜欢,则用户无法删除帖子,它以前正在工作,但是当我将帖子与喜欢链接时,我一直收到此错误,我甚至无法在Sequel Pro中删除它,除非我首先删除与帖子相关的喜欢。
错误
SQLSTATE[23000]:完整性约束冲突:1451 无法删除或更新父行:外键约束失败(.,约束外键 () 引用 ()) (SQL:从中删除 = 149)
eliapi8
likes
likes_post_id_foreign
post_id
posts
id
posts
id
也许是我的模式?
帖子架构
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();
});
我可以喜欢帖子,也可以不喜欢帖子,但用户不能删除被赞的帖子。
后控制器.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);
}