Heim  >  Artikel  >  Backend-Entwicklung  >  Yii - relations数据关联中的统计功能_PHP教程

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

WBOY
WBOYOriginal
2016-07-14 10:10:00793Durchsuche

关联查询,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'),
        );
    }
}

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477598.htmlTechArticle关联查询,Yii 也支持所谓的统计查询(或聚合查询)。 它指的是检索关联对象的聚合信息,例如每个 post 的评论的数量,每个产品的平均等级...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn