代码之家  ›  专栏  ›  技术社区  ›  slickness

全队得分

  •  0
  • slickness  · 技术社区  · 6 年前

    每个用户有一个团队,每个团队有几个用户。相应的团队id存储在用户表中。

    下面我计算Auth::User的所有点,并在视图中显示给他。我的问题是,如何计算和显示每个团队的分数,以及如何向用户显示他们各自团队的分数?

    我可以在所有队伍的列表中显示各个队伍的得分。

        $start = 200;
        $invitations = 50;
        $postp = 10;
        $commentp = 5;
    
        $postpup = 3;
        $postpdown = -4;
        $commentpup = 2;
        $commentpdown = -3;
        $userpostpup = 2;
        $userpostpdown = 1;
        $usercommentpup = 2;
        $usercommentpdown = 1;
    
        $invitedpoints = User::where('invited_from_id','=', $user->id)->count()*$invitations;
        $postpoints = $user->posts->count()*$postp;
        $commentpoints = $user->comments->count()*$commentp;
    
        //---get rating from users on created posts and comments---\\
        $postvotepointsup = Post::where('status', 1)->where('posts.user_id', $user->id)->upVotesAll()->count()*$postpup;
        $postvotepointsdown = Post::where('status', 1)->where('posts.user_id', $user->id)->downVotesAll()->count()*$postpdown;
        $commentvotepointsup = Comment::where('status', 1)->where('comments.user_id', $user->id)->upVotesAll()->count()*$commentpup;
        $commentvotepointsdown = Comment::where('status', 1)->where('comments.user_id', $user->id)->downVotesAll()->count()*$commentpdown;
    
        //---voted by user---\\
        $userpostvotepointsup = Post_activity::where('user_id','=', $user->id)->where('activity',1)->count()*$userpostpup;
        $userpostvotepointsdown = Post_activity::where('user_id','=', $user->id)->where('activity',0)->count()*$userpostpdown;
        $usercommentvotepointsup = Comment_activity::where('user_id','=', $user->id)->where('activity',1)->count()*$usercommentpup;
        $usercommentvotepointsdown = Comment_activity::where('user_id','=', $user->id)->where('activity',0)->count()*$usercommentpdown;
    
        $totaluserpoints =$start+$postpoints+$commentpoints+$invitedpoints+$postvotepointsup+$postvotepointsdown+$commentvotepointsup+$commentvotepointsdown+$userpostvotepointsup+$userpostvotepointsdown+$usercommentvotepointsup+$usercommentvotepointsdown;
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   redcenter    6 年前

    class User extends Model {
        public function points(){
        .. your point logic ..
        }
    }
    

    然后在控制器中,但在其他地方更好:让团队中的所有用户检索集合。

    $collection = $team->users()->all();
    

    然后你在集合中循环,同时计算所有单个用户的用户点数。。。

    $collection->sum(function(User $user){
        return $user->points();
    });
    

    class Team extends Model {
        public function getTotalUserPoints(){
    
           $allUsers = $team->users()->all();
    
           return $allUsers->sum(function(User $user){
                 return $user->points();
           });
        }
    }
    

    您只需执行以下操作即可获得团队的总金额:

    $team->getTotalUserPoints()
    

    $user->points()
    

    要通过单个用户获得团队总数:

    $user->team->getTotalUserpoints()