Specify ActiveRecord relation count


I would like to ask for some advice on counting active record relations.

I have a table called Groups, and it has id and parent_id fields. A group can have a parent group by setting the parent’s id as the parent_id value.

+----------+           G

|  Groups  |         /   \

+----------+       G       G  

| id       |      / \     / \

| parent_id|     G   G   G   G


I have defined these relations so far:

'parent'=>array(self::BELONGS_TO,'Group','parent_id'), // belongs_to -> parent_id means the field in the current table

'children'=>array(self::HAS_MANY,'Group','parent_id'), // has_many -> parent_id means the field in the other table(s)

I would like to also define a parentCount and a childrenCount relation. I always user the self::STAT, but if I use it here, it is ambiguous.



The STAT relation definition is the same for them. I’m guessing it gives back only the parentCount (so the STAT version of BELONGS_TO), and I don’t know how to define the STAT for the HAS_MANY relation.

How can I specifiy that I would like to create a statistical query for the children or for the parent?

Any help would be appreciated!

Try with:



Thanks for the reply. However, it does not work, it says "The relation "childrenCount" in active record class "Group" is specified with an invalid foreign key "childrenCount.parent_id". There is no such column in the table "Groups"."

But there clearly is a parent_id field in the table (I guess it tries to access the "childrenCount.parent_id" field not the "parent_id" field).

Altough I realized, that since every group has one or zero parents, the parentCount is pretty useless. And the self::STAT relation gives back the childrenCount so by default the STAT version of BELONGS_TO, which is perfect for me, and the problem is solved.

However if anyone knows how to specify STAT query for amiguous columns, please tell, I’m still curious.

If it doesn’t work with self::STAT, you can achieve a similar approach with two functions:

class Groups


	public function getParentCount()


		$parent = $this->parent;



	public function getChildrenCount()


		$children = $this->children;