July 9, 2012, 10:14pm
I would like to know if there is a way to count the records retrieved when a relation is used.
Supposing we have a User table with a HAS_MANY relation to a table "address"
$user = User::model()->findByPk(1234);
echo $user->addresses->count(); <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />??
If we can’t do it like this, what is the quickest/best way to do so?
Thanks in advance!
July 10, 2012, 7:40am
i think you can use a STAT relation (if you’re using activeRecord):
July 11, 2012, 6:38pm
Thanks for your reply!
I read the documentation, but I don’t quite understand in what way it is statistical…
Do you have a simple example of how can I use it to do what I want?
July 12, 2012, 7:46am
public function relations()
'relStudentSemesters' => array(self::HAS_MANY, 'RelStudentSemester', 'group_id'),
'studCount'=>array(self::STAT, 'RelStudentSemester', 'group_id'),
The table group is related to the table relStudentSemesters, and i use a stat field (which is not in the database, by definition) to have direct response to the question: how much RelStudentSemesters are related to the group number x.
July 12, 2012, 11:39am
As i understand relations are arrays, so why not to use:
October 8, 2012, 7:24am
$user->addresses <=> sql = "SELECT *
LEFT OUTER JOINuser
.id` = 1;
result get many recdords.
count($user->addresses) = count array php.
"if 1 million records, it is dangerous for your system"
$user->stat_relation_count <=> SELECT
u, COUNT(*) AS
t WHERE (
user_id=‘2’) GROUP BY
result get 1 record, this count record by mysql.
you can use yii toolbar see sql, and use EXPLAIN query check performance two sql. relation STAT is more optimal.
very happy if my comments help you!
I can not write good English. I hope you to understand my interpretation.
For anyone, who came to this thread to find out a way on how to get count of related items without writing STAT relation by hands - I wrote an extension for this:
it works for me.
$postcount = Post::model()->count();