執行統計查詢非常類似於之前描述的關聯查詢。我們首先需要在 CActiveRecord 的 relations() 方法中聲明統計查詢。
- 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 的所有審覈後的評論。
- class User extends CActiveRecord
- {
- public function relations()
- {
- return array(
- 'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'with'=>'comments:approved'),
- );
- }
- }