计算整个团队的积分

时间:2018-10-10 15:18:49

标签: php laravel count one-to-many

每个用户都有一个团队,每个团队都有多个用户。各个team_id存储在用户表中。

下面,我计算Auth ::用户的所有要点,并在“视图”中将其显示给他。我的问题是,我该如何计算和显示每个团队的积分,以便可以向用户显示他们各自团队的积分?

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

// ---------用户点--------- \

    $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 个答案:

答案 0 :(得分:2)

我会做这样的事情...请注意:这是PSEUDO代码,只是为了显示解决方案的方向...

将积分逻辑移动到用户模型

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

同样,伪代码只是为了让人们了解从何开始。这样,您就可以将所有关于点的业务逻辑(一个用户模型)放在一个地方,但是您可以使用它来获取总分和单个分。