php关联统计,Yii - relations数据关联中的统计功能_PHP教程

关联查询,Yii 也支持所谓的统计查询(或聚合查询)。 它指的是检索关联对象的聚合信息,例如每个 post 的评论的数量,每个产品的平均等级等。 统计查询只被 HAS_MANY(例如,一个 post 有很多评论) 或 MANY_MANY (例如,一个 post 属于很多分类和一个 category 有很多 post) 关联对象执行。

执行统计查询非常类似于之前描述的关联查询。我们首先需要在 CActiveRecord 的 relations() 方法中声明统计查询。

[html]

class Post extends CActiveRecord

{

public function relations()

{

return array(

'commentCount'=>array(self::STAT, 'Comment', 'post_id'),

'categoryCount'=>array(self::STAT, 'Category', 'post_category(post_id,category_id)'),

);

}

}

class Post extends CActiveRecord

{

public function relations()

{

return array(

'commentCount'=>array(self::STAT, 'Comment', 'post_id'),

'categoryCount'=>array(self::STAT, 'Category', 'post_category(post_id,category_id)'),

);

}

}关联查询命名空间

关联查询也可以和 命名空间一起执行。有两种形式。第一种形式,命名空间被应用到主模型。第二种形式,命名空间被应用到关联模型。

下面的代码展示了如何应用命名空间到主模型。

$posts=Post::model()->published()->recently()->with('comments')->findAll();

这非常类似于非关联的查询。唯一的不同是我们在命名空间后使用了 with() 调用。 此查询应当返回最近发布的 post和它们的评论。

下面的代码展示了如何应用命名空间到关联模型。

$posts=Post::model()->with('comments:recently:approved')->findAll();

上面的查询将返回所有的 post 及它们审核后的评论。注意 comments 指的是关联名字,而 recently 和 approved 指的是 在 Comment 模型类中声明的命名空间。关联名字和命名空间应当由冒号分隔。

命名空间也可以在 CActiveRecord::relations() 中声明的关联规则的 with 选项中指定。在下面的例子中, 若我们访问 $user->posts,它将返回此post 的所有审核后的评论。

[html]

class User extends CActiveRecord

{

public function relations()

{

return array(

'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'with'=>'comments:approved'),

);

}

}

class User extends CActiveRecord

{

public function relations()

{

return array(

'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'with'=>'comments:approved'),

);

}

}

http://www.bkjia.com/PHPjc/477598.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/477598.htmlTechArticle关联查询,Yii 也支持所谓的统计查询(或聚合查询)。 它指的是检索关联对象的聚合信息,例如每个 post 的评论的数量,每个产品的平均等级...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值