2 Problems With Relational Active Records

(Appinger2012) #1


I’m new here and new with the Yii Framework.

Now I like to work with Relational Active Record.

Two Problems:


I’d like to count the number of trees in an area. A tree is in a city and a city is in a region. Now I would like to return the number of trees in the region with ID 1.

In region-model stands in the relations:

return array (‘city’ => array (self :: HAS_MANY, ‘city’, ‘RegionlD’));

In the city-model stands in the relations:

return array (‘tree’ => array (self :: HAS_MANY, ‘tree’, ‘StadtID’));

So how can I count the trees?


I like to select all trees in a Region with ID=1.

I tryed

Tree::model()->with(‘city’)->with(‘region’)->findAll(‘Region.ID=:id’, array(‘id’ => 1));

but the Tree Model does not know region.

Can anybody help me?


(Kburton) #2

For your second question, assuming you’ve already configured those relations, try:


For your first question, you could retrieve all of the records as above and return the count of them, but that may be inefficient if your data set is large. Alternatively, look into using the STAT relation type or consider a custom query using PDO.

EDIT: Also, make sure you have a ‘region’ relation in your City model.

'region' => array(self::BELONGS_TO, 'Region', 'RegionID')

(Appinger2012) #3

Thanks for the answer.

In the city-model i also insert the relation

'region' => array(self::BELONGS_TO, 'Region', 'RegionID')

but there is the error:

table "Tree" has no column named "region.id"

(Chellamnivas) #4

Dear Appinger

Would you please try this?

In Region Model.

return array (

       'city' => array (self :: HAS_MANY, 'city', 'RegionlD'),

       'tree' => array (self :: HAS_MANY, 'tree', array('id'=>'StadtID'),'through'=>'city'),



Then try doing following this.


echo count($trees);


(Appinger2012) #5


This works fine.

But how can I do actions like order or limit the trees? For example order trees by size?

(Chellamnivas) #6

Dear Appinger

We can do this way.




'order'=>'size DESC'



(Appinger2012) #7

Worked great!