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

BAR*_*OWL 10 mysql laravel

由于某些原因,用户无法删除帖子,如果它已被喜欢,它之前正在工作,但当我链接帖子与喜欢我一直收到此错误,我甚至无法删除它在续集专业版,除非我删除相关的喜欢先发帖子.

错误

SQLSTATE [23000]:完整性约束违规:1451无法删除或更新父行:外键约束失败(eliapi8.likes,CONSTRAINT likes_post_id_foreignFOREIGN KEY(post_id)REFERENCES posts(id))(SQL:delete from postswhere id= 149)

Mac上的续集专业版

也许这是我的架构?

帖子架构

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();
});
Run Code Online (Sandbox Code Playgroud)

喜欢Schema

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();
});
Run Code Online (Sandbox Code Playgroud)

我喜欢和不喜欢的帖子,但用户无法删除已被喜欢的帖子.

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);
}
Run Code Online (Sandbox Code Playgroud)

Cam*_*ilo 22

是的,这是你的架构.约束likes.post_id将阻止您从posts表中删除记录.

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

Schema::create('likes', function (Blueprint $table) {
    // Some other fields...

    $table->integer('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
Run Code Online (Sandbox Code Playgroud)

这样,当删除帖子时,所有相关的喜欢也将被删除.

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


Tia*_*ica 11

我已经测试过,onDelete('cascade')但就我而言,它不起作用。我尝试删除的资源有一个模型hasMany()

/**
 * Get the departments of the organization
 *
 * @return void
 */
public function org_departments()
{
    return $this->hasMany(Department::class);
}
Run Code Online (Sandbox Code Playgroud)

所以,在destroy()控制器中OrganizationUserController,而不是有

$organization->delete();
Run Code Online (Sandbox Code Playgroud)

我确保首先删除该组织的部门,然后才删除$organization

$organization->org_departments()->delete();

$organization->delete();
Run Code Online (Sandbox Code Playgroud)

然后就被删掉了就好了。