将计数变量附加到对象

时间:2013-04-23 12:51:50

标签: yii counting cgridview

我需要一些帮助来显示CGridView中每个用户的帖子数。

例如: 我有一个User和Post模型。 我可以通过$ user->帖子访问用户的帖子 有什么我可以添加到$ user-> num_posts

2 个答案:

答案 0 :(得分:2)

您应该只使用统计关系,例如在您的用户模型中:

public function relations()
{
  return array(

    // ...
    'posts' => array(self::HAS_MANY, 'Post', 'user_id'),
    'num_posts' => array(self::STAT, 'Post', 'user_id'),
    // ...

  );
}

http://www.yiiframework.com/doc/guide/1.1/fr/database.arr#statistical-query

编辑: 您还应该使用预先加载来构建数据提供者,例如:

$criteria=new CDbCriteria;
$criteria->with('num_posts');

关于SQL查询,这应该只使用3个查询:

  • 对gridview页面计数的一个查询,
  • 获取用户模型的一个查询,
  • 获取用户num_posts的一个查询。

只需看看Yii日志即可。

答案 1 :(得分:-1)

您可以在Post模型中使用getter。 像这样:

public static function getpostscount($id)
    {
        $total=0;
        $provider=Post::model()->findall('user_id=:user_id',array(':user_id'=>$id));
        foreach ($provider as $data)
        {
                if ($data->userid==$id)//userid name of column with user id in post model
                {$total++;
                }

        }
        return $total;
    }

然后在您的视图中,只需将user-> id传递给getter,它就会返回此用户的帖子数。像这样:

echo "User have".Post::model()->getpostscount($user->id);//$user->id is id of user for wich we will look count of posts

问候。