2 Problems With Relational Active Records
Posted 22 November 2012 - 10:05 AM
I'm new here and new with the Yii Framework.
Now I like to work with Relational Active Record.
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.
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?
Posted 22 November 2012 - 10:29 AM
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')
Posted 22 November 2012 - 12:12 PM
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.
$trees=Region::model()->findByPk(1)->tree; echo count($trees);