M
M
microf2014-11-01 17:31:03
MySQL
microf, 2014-11-01 17:31:03

How to count quantity with ActiveRecord?

Good afternoon.
How to count the number of cities in a table?
`id`,`user`,`country_id`,`city_id`
How to get just the number of records - understandable
<?= User::find()->count()?>
And how to calculate the number of cities a user has?
I don’t understand the query itself by counting unique cities

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
max7 M7, 2014-11-01
@microf

1. SELECT COUNT(DISTINCT `city_id`) AS `city_count`  FROM `user_table`;
2. SELECT `user`, COUNT(DISTINCT `city_id`) AS `city_count` FROM `user_table` GROUP BY `user`;

A
Alexander, 2014-11-03
@misantron

You can use a realation like stat.
Here is an example code for your case:

class User extends CActiveRecord
{
    public function relations()
    {
        return array(
            'cityCount'=>array(self::STAT, 'City', 'city_id'),
        );
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question