For some reason a user cannot delete a post if it has been liked, it was working before but when I linked posts with likes I have been getting this error, I can't even delete it in Sequel Pro, unless I delete the likes associated with the post first.

Error

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (eliapi8.likes, CONSTRAINT likes_post_id_foreign FOREIGN KEY (post_id) REFERENCES posts (id)) (SQL: delete from posts where id = 149)

Sequel Pro on Mac

也许是我的图式吧?

Posts Schema

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

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

I can like and unlike a post, but a user cannot delete a post that has been liked.

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

推荐答案

Yes, it's your schema. The constraint on likes.post_id will prevent you from deleting records from the posts table.

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

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

这样,当一个帖子被删除时,所有相关的点赞也会被删除.

或者,如果您有一个从Post模型到LIKE模型的关系,您可以在删除帖子本身之前输入$post->likes()->delete().

Laravel相关问答推荐

如何判断用户是否已登录Laravel

通过 laravel 中的 url 传递多个字符串作为参数以从数据库中删除特定数据

API GET 请求得到与数据库记录不同的结果

前端和管理员分开时未加载laravel 9中间件

Laravel 6 Passport 在错误的凭证上返回 400 Bad request

自定义 Laravel 关系?

Laravel 中的 index()" 是什么意思?

Guzzle - Laravel如何使用 x-www-form-url-encoded 发出请求

具有实时和 WebSockets 的 Angular2 + Laravel

Laravel Eloquent Pluck 不丢失密钥

需要 Vagrant 环境或目标机器

将 Laravel Socialite 与 API 一起使用?

为什么客户凭证应该与 Laravel Passport 中的用户相关联?

Laravel assets资源与混合

如何在 Laravel 或 Redis 中取消排队的作业(job)

Laravel Eloquent模型如何从关系表中获取数据

在 laravel 的测试套件中只运行一个单元测试

Laravel 验证存在于不存在的地方

开发中的 Laravel 和视图缓存 - 无法立即看到更改

限制自己重载外部 API 的速率