Home>

Relational query,Yii also supports so-called statistical queries (or aggregate queries). It refers to retrieving aggregated information of related objects,Such as the number of comments per post,The average level of each product, etc. Statistical queries are only performed by has_many (for example, a post with many comments) or many_many (for example, a post belongs to many categories and a category has many posts) associated objects.

Performing a statistical query is very similar to the correlated query described earlier.We first need to declare statistical queries in cactiverecord's relations () method.

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)"),    );
  }
}

Associative query namespace

Correlation queries can also be performed with namespaces.There are two forms.The first form,The namespace is applied to the main model.The second form,Namespaces are applied to the association model.

The following code shows how to apply a namespace to the main model.

$posts=post ::model ()->published ()->recently ()->with ("comments")->findall ();

This is very similar to a non-associative query.The only difference is that we use the with () call after the namespace. This query should return the most recently posted posts and their comments.

The following code shows how to apply a namespace to an association model.

$posts=post ::model ()->with ("comments:recently:approved")->findall ();

The above query will return all posts and their reviewed comments.Note that comments refer to association names,And recently and approved refer to namespaces declared in the comment model class.The associated name and namespace should be separated by a colon.

The namespace can also be specified in the with option of the association rule declared in cactiverecord ::relations ().In the following example, If we visit $user->posts, it will return all reviewed comments for this post.

class user extends cactiverecord
{
  public function relations ()
  {
    return array (
      "posts" =>array (self ::has_many, "post", "author_id", "with" =>"comments:approved"),    );
  }
}
php
  • Previous Yii programming development common call skills collection
  • Next Jquery implements a simple example of the mask layer (that is, the pop-up DIV is gray and cannot be operated around)