0

我试图比较我从用户那里得到的数字和存储在数据库中的数字。

基本上,我正在做一个奖励系统,达到一定积分的用户将获得一个徽章。现在,我正在做的是,代码将计算用户拥有的积分并将其发送到具有 if else 的函数来比较积分和每个徽章的值。

我现在想要做的是,通过将每个徽章的值放在数据库中来使其更简单,这样下次我就可以更新数据库而不更新代码。以下是我现在正在做的事情。

//check total points that the user has
public function totalPointsValue($userId) {

    $value = Yii::app()->db->createCommand()
        ->select('sum(totalPoints) as pointsSum')
        ->from('fndn_UserTotal')
        ->where('userId =:id', array(':id'=>$userId))
        ->queryRow();

    $totalPoints = $value['pointsSum'];

    return $totalPoints;
}

//checks whether the user points is enough for a badge
public function checkEligable($userId){

    $points = $this->totalPointsValue($userId);

    //is not eligable for a badge
    if ($points <100){
        error_log(" $userId has less than 100 points. Number of points is $points ");
    }

    //eligable for the over 100 points badge
    elseif ($points > 100 && $points <1000){
        error_log(" $userId is eligable for over-100 badge. Number of points is $points ");


    }

    //eligable for the over 1000 points badge
    elseif ($points > 1000 && $points <2000){
        error_log(" $userId is eligable for over-1000 badge. Number of points is $points ");


    }

    //eligable for the over 2000 points badge
    else {
        error_log(" $userId is eligable for over-2000 badge. Number of points is $points ");


    }

    error_log(print_r($points, true), 3, 'debug.log');

}

我想让代码检查数据库中的值并将其与 $points 进行比较。下面是我的徽章数据库。

===============

id         badgeName        requiredPoints
1          over100            100
2          over500            500
3          over1000           1000 
4          over2000           2000 

所以,假设用户有 600 分,它会检查用户有权获得哪个徽章。如果 $points > requirePoints,它将授予用户徽章。

4

1 回答 1

0

假设您有表和模型名称徽章。

编辑:如果您只想要最接近用户获得的徽章级别

function getBadgesOfUser($points){
        $achive_badges = "";
        $badges = CHtml::listData(Badge::model()->findAll(array(
            'order'=>'requiredPoints', // ASC
            'condition'=>'requiredPoints>=:rqp',
            'params'=>array('rqp'=>$points))), 'badgeName', 'requiredPoints');

        if(count($badges)>0){
          //php 5.4
            $achive_badges = array_keys($badges)[0]; // I don't use array_shift in this line because it would cause the warning raising in some cases.

           //following for PHP 5.3
           $temp = array_keys($badges); $achive_badges = $temp[0];

        }
        return $achive_badges;
}

我使用比较运算符在查询中进行排序,这意味着该requirePoints列的数据类型必须是数字(int,decimal等)

于 2013-10-23T04:48:39.867 回答