【发布时间】:2018-05-12 15:36:04
【问题描述】:
由于某种原因,如果帖子已被点赞,则用户无法删除该帖子,它以前可以使用,但是当我将帖子与点赞链接时,我收到此错误,我什至无法在 Sequel Pro 中删除它,除非我删除与帖子相关的喜欢优先。
错误
SQLSTATE[23000]:违反完整性约束: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);
}
【问题讨论】: