appinger
(Appinger2012)
November 22, 2012, 3:05pm
1
Hello,
I’m new here and new with the Yii Framework.
Now I like to work with Relational Active Record.
Two Problems:
1.)
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?
2.)
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?
Thanks…
Keith
(Kburton)
November 22, 2012, 3:29pm
2
For your second question, assuming you’ve already configured those relations, try:
Tree::model()->with('city.region')->findAllByAttributes(array('region.id'=>1)));
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')
appinger
(Appinger2012)
November 22, 2012, 5:00pm
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"
seenivasan
(Chellamnivas)
November 22, 2012, 5:12pm
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.
$trees=Region::model()->findByPk(1)->tree;
echo count($trees);
Regards.
appinger
(Appinger2012)
November 23, 2012, 12:26pm
5
Thanks!
This works fine.
But how can I do actions like order or limit the trees? For example order trees by size?
seenivasan
(Chellamnivas)
November 23, 2012, 7:34pm
6
Dear Appinger
We can do this way.
$trees=Region::model()->with(array('tree'=>array(
'select'=>'tree.id,site,owner,size',
'condition'=>'size<2',
'order'=>'size DESC'
)))->findByPk(1)->tree;
Regards