由于某种原因,用户不能删除一个帖子,如果它是喜欢的,它以前是工作的,但当我链接的帖子和喜欢我已经得到这个错误,我甚至不能删除它在续集Pro,除非我删除喜欢与文章有关的第一。
误差
SQLSTATE23000:完整性约束违反: 1451不能删除或更新父行:外键约束失败(
eliapi8.likes,约束likes_post_id_foreign外键(post_id)引用posts(id)) (SQL:从posts中删除id= 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);
}发布于 2021-03-04 13:03:06
我已经用onDelete('cascade')进行了测试,但在我的例子中,它没有起作用。我试图删除的资源有一个带有hasMany()的模型。
/**
* Get the departments of the organization
*
* @return void
*/
public function org_departments()
{
return $this->hasMany(Department::class);
}因此,在控制器destroy()的OrganizationUserController中,而不是
$organization->delete();我保证先删除那个组织的部门,然后再删除$organization,
$organization->org_departments()->delete();
$organization->delete();然后它就被删除了。
发布于 2021-08-30 07:27:44
如果您处于生产模式,只需production迁移:鲜活。它会丢弃所有的表
注:记录将从表中删除
你为什么要面对这个问题??
实际上,您不能删除在子表中具有数据的父表。首先,您必须删除子表数据,而不是删除父表。
您有两个选项来处理这个问题。
1)->onDelete(“级联”)在迁移中使用您的专用密钥
2)如果您在控制器中,首先删除$organization->org_departments()->delete();因此,您的所有子节点都会首先被删除,而不是删除父子$organization-> delete ();
发布于 2022-01-06 16:22:58
将on delete改为cascade,而不是restrict。

https://stackoverflow.com/questions/47544109
复制相似问题