您好,欢迎访问一九零五行业门户网

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 的评论的数量,每个产品的平均等级...
其它类似信息

推荐信息