比较从数据库和代码 Yii 中获取的值


Compare values taken from database and code Yii

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

基本上,我正在做一个奖励系统,达到一定数量积分的用户将获得一个徽章。 现在,我正在做的是,代码将计算用户拥有的积分并将其发送到具有 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>需要积分,它将授予用户徽章。

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

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

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列的数据类型必须是数字(整数、十进制等)