【发布时间】:2013-04-23 12:51:50
【问题描述】:
我需要一些帮助才能在 CGridView 中显示每个用户的帖子数。
例如: 我有一个用户和帖子模型。 我可以通过 $user->posts 访问用户的帖子 有什么我可以添加到 $user->num_posts
【问题讨论】:
我需要一些帮助才能在 CGridView 中显示每个用户的帖子数。
例如: 我有一个用户和帖子模型。 我可以通过 $user->posts 访问用户的帖子 有什么我可以添加到 $user->num_posts
【问题讨论】:
您应该简单地使用统计关系,例如在您的用户模型中:
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 个查询:
看看 Yii 日志就可以确定了。
【讨论】:
您可以在 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
问候。
【讨论】:
$provider=Lists::model()->findall('user_id=:user_id', array(':user_id'=> $criteria));。