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

2022-08-30 16:01:26

由于某种原因,如果帖子已被喜欢,则用户无法删除帖子,它以前正在工作,但是当我将帖子与喜欢链接时,我一直收到此错误,我甚至无法在Sequel Pro中删除它,除非我首先删除与帖子相关的喜欢。

错误

SQLSTATE[23000]:完整性约束冲突:1451 无法删除或更新父行:外键约束失败(.,约束外键 () 引用 ()) (SQL:从中删除 = 149)eliapi8likeslikes_post_id_foreignpost_idpostsidpostsid

也许是我的模式?

帖子架构

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);
}

答案 1

是的,这是您的架构。上的约束将阻止您从表中删除记录。likes.post_idposts

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

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

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

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


答案 2

我已经测试过,但在我的情况下它不起作用。我尝试删除的资源具有一个具有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();

然后它被删除了就好了。


推荐