When I try to use CDbCriteria to count records I get Active record “Hotels” is trying to select an invalid column “count(t.id) as count“.
Here is my code:
$criteria = new CDbCriteria();
$criteria->select = 'count(t.id) as `count`, t.`keywords`, min(offers.first_bookin) as first_bookin';
$criteria->with = array('offers');
$criteria->group = 'offers.hotels_id';
$criteria->compare('first_bookin','>' . date('Y-m-d'));
$criteria->together = true;
$hotelItems = Hotels::model()->findAll($criteria);
And here are my relations defined in Hotels model:
return array(
'headers' => array(self::HAS_MANY, 'Headers', 'hotels_id'),
'offers' => array(self::HAS_MANY, 'Offers', 'hotels_id'),
);
I red a lot of posts here and on some other sites, but nothing seems to work. I tried with count(*), count(id), I tried splitting the select property into an array. Every time I get the same error.
Just remove the backticks from the alias and the count should work. Of course if you want to access the count easily you will have to declare it as a class variable, as mentioned by onkarjanwa.
If you check the source of the error, it’s this function:
getColumnSelectofCActiveFinder, the select for count should satisfy this line, ingetColumnSelect:but because of the backticks in the alias name, it doesn’t match, and it throws an error. So your
selectshould be without the backticks for aliases:When i was testing this, i got another error in your
compare, so you should change it to: