简体   繁体   English

yii行的求和值

[英]summing value of row yii

I have a table where i store the userId, and points. 我有一个表,我在其中存储userId和点。 Everytime a user uses a transaction, they will be awarded points and these points are stored in UserPoints. 每次用户使用交易时,将获得积分,并将这些积分存储在UserPoints中。 It will post new rows for each transaction. 它将为每个事务发布新行。

id | id | userId | userId | points 点数

1 2 38 1 2 38

2 18 50 2 18 50

3 2 12 3 2 12

4 10 13 4 10 13

5 15 15 5 15 15

like the table above, userID 2 has multiple lines, i want to add all the value that userId 2 have. 像上表一样,userID 2有多行,我想添加userId 2具有的所有值。 i want to put the calculation inside the model MUserTotal inside the variable totalPointsValue(). 我想将计算放在变量totalPointsValue()中的模型MUserTotal中。

Here is what i have so far 这是我到目前为止所拥有的

public function totalPointsValue() {

    user = $this->userId;

}         

What you need is statical query . 您需要的是静态查询

Basically you create a relation ship on the user Class to the UserPoints of type STAT, and specify the criteria: 基本上,您在用户类上创建与STAT类型的UserPoints的关系,并指定条件:

<?php
class User extends CActiveRecord
{
    public function relations()
    {
        return array(
            'points'=>array(
                self::STAT, // Declare this relation as statical
                'user_points', // The table where you are storing the points
                'userId', // The foreign key on that table
                'select' => "SUM(points)", // make it SUM instead of default COUNT
                'group' => "userId" // Group by this field when adding points
            ),
        );
    }
}

After that you can use the relationship as you would use any other: 之后,您可以像使用其他任何关系一样使用关系:

<?php
$user = User::model()->findbyPk(1);
echo $user->points;

or if you need to create the model MUserTotal ... just create a view that contains the userId and sum of his points, and create the model for this view ... the query will be some thing like 或者,如果您需要创建模型MUserTotal ...,只需创建一个包含userId和他的积分之和的视图,然后为此视图创建模型...查询将类似于
select user_id, sum(points) from user_points group by user_id 选择user_id,按user_id从user_points组中求和(点)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM