计算关系表行

时间:2013-05-03 04:51:37

标签: php mysql yii

我正在尝试计算关系表many to many中的行数,但总是返回错误的值。当它为1时,总是返回2.

PS:mysql中的所有模型和外键都配置正确。

评论表:

id  |  name
10      Comment Test

用户表:

id  |  name
20     User Test

喜欢(评论/用户)多对多:

user_id  |  comment_id
20          10

代码:

$criteria = new CDbCriteria;
$criteria->select='*, COUNT(likes.id) AS count_likes'; // I believe the error is in the use of COUNT (likes.id).
$criteria->with=array('likes'=>array('on'=>'user_id=20'));
$model = Comments::model()->findByPk($_GET['id'], $criteria);

// Return Wrong Value
echo $model->count_likes; // Return 2 where should be 1. (I need to use this case)
echo count($model->likes); // Return right value 1.

2 个答案:

答案 0 :(得分:2)

您应该使用Statistical Query,例如:

在评论模型中:

public function relations()
{
    return array(
        // ...

        // I assume your relation table's name is "likes"
        'likes'=>array(self::MANY_MANY, 'Users', 'likes(comment_id, user_id)'),
        'likesCount'=>array(self::STAT, 'Users', 'likes(comment_id, user_id)'),

        // ...
    );
}

答案 1 :(得分:0)

您是否计划从LIKES表中选择并按用户ID和评论ID进行分组?
如果是这样,您可以使用 GROUP BY 请在这里查看SQLFiddle
http://sqlfiddle.com/#!2/bc29b8/1/0
SELECT uid, cid, COUNT(likes.cid) FROM likes GROUP BY uid, cid