yii如何从db表中查找总和?

时间:2013-06-06 16:33:00

标签: yii yii-extensions

大家好,感谢您的阅读

我有两张桌子; 第一张表是主表,它是我的成本,

第二个表是一个表,其中我有与这些成本相关联的用户。

我想知道是否有人可以指出我正确的方向来实现以下目标; 创建一个yii STAT查询,返回特定用户所有成本的总和。 这是我在mysql中所做的,我想将其转换为yii格式;

    select sum(cost) from tbl_bridge_contract a
join tbl_employer_contract b using(id_employer_contract)
where a.user_id=4

1 个答案:

答案 0 :(得分:1)

不确定您的数据库架构是什么样的..但我们假设我们有两个模型(数据库中的表) - PostComment

Comment是指Posttbl_comment外键是指tbl_post的主键。这意味着Post HAS_MANY Comment。根据此,您的Post::relations方法可能如下所示:

/**
 * @return array
 */
public function relations()
{
    return array(
        'comments' => array(self::HAS_MANY, 'Comment', 'post_id'), // <-- post_id is FK in tbl_comment
        'countComments' => array(self::STAT, 'Comment', 'post_id'), // <-- the same as above, post_id is FK in tbl_comment
    );
}

然后在任何地方(比如在控制器中)你这样做:

$post=Post::model()->findByPk(731);

var_dump($post->comments); // <-- dumps array of Comment-models, if any
var_dump($post->countComments); // <-- dumps number of related comments

当然,您应该阅读此http://www.yiiframework.com/doc/guide/1.1/en/database.arr#statistical-query

我希望这会有所帮助。