【问题标题】:laravel withCount get likes that have been deletedlaravel withCount 获取已删除的赞
【发布时间】:2018-05-13 07:04:51
【问题描述】:

此函数不计算已删除的帖子。它只是计算总点赞数,但忽略 deleted_at is = null

我正在使用软删除来满足我的喜好。

我正在尝试计算一个帖子的点赞数,其中 deleted_at 为 == 为 null(表示未删除的点赞数)。

无论它是否被软删除,它似乎都忽略了我拥有的东西并获得了所有喜欢的东西。

这是我目前拥有的。

public function getTotalLikes(Post $post, User $user)
{

    $likes = Post::withCount('likes')->first();

    if($likes->deleted_at != NULL){
        return 'no likes';
    }


    else{
        return $likes->count();
    }

    $response = new Response(json_encode($likes));
    $response->headers->set('Content-Type', 'application/json'); 

    return $response;
}

【问题讨论】:

  • withCount 应该尊重软删除,如indicated here。你确定你已经为喜欢正确配置了软删除吗? Like::all() 是否显示软删除记录?
  • 让我尝试一下,是的,我确实正确配置了软删除,这是有趣的事情,如果我在上面的函数上拼错了 deleted_at,它不会显示任何错误,它将继续执行该函数 -
  • 它忽略了这个if($likes->deleted_at != NULL){ return 'no likes'; } 部分
  • 你能显示 likes() 关系吗?也许你有 withTrashed 那里...
  • 我有一个 Heroku 用于此注册和登录并查看网络标签 morning-depths-45941.herokuapp.com

标签: php laravel


【解决方案1】:

试试这个方法:

public function getTotalLikes(Post $post)
{
    $likes = Like::where('post_id', $post->id)->get();

    if($likes->count()){
        return $likes->count();
    }
    return 'no likes';
}

在 Js 中:

$scope.getLikecount = function(post){
    $http.get('post/'+post.id+'/getTotalLikes').then(function(result){

        console.log("likes:"+result.data);

    });

};

在路由文件中:

Route::get('post/{post}/getTotalLikes', 'PostController@getTotalLikes');

关于 laravel 中的软删除的附注:

当你做这样的事情时:

Like::where('post_id', $post->id)->get();

Laravel 排除自动删除的,
如果您想要即使是已删除的,也可以添加withTrashed()

Like::withTrashed()->where('post_id', $post->id)->get();

当你想要只删除那些使用onlyTrashed()

Like::onlyTrashed()->where('post_id', $post->id)->get();

【讨论】:

  • 嘿伙计 :) 你有什么理由评论掉回复?
  • 是的,有一个 :p,因为你已经完成了 return 'no likes';return $postWithCount->likes_count; 所以响应块是一个死代码;)(不会到达)!
  • 我在一秒钟内测试这个
  • 是的,我试过$count = Likes::where('post_id', $post->id)->count();,当有帖子被点赞时,它只会呈现0
  • 我可以将这个 heroku 推送一秒
猜你喜欢
  • 1970-01-01
  • 2021-05-08
  • 2014-12-31
  • 2020-01-30
  • 2020-05-29
  • 2019-03-27
  • 2023-03-28
  • 2015-02-18
  • 1970-01-01
相关资源
最近更新 更多