Reputation: 1259
$criteria=new CDbCriteria();
$criteria->with = array('reviewCount', 'category10', 'category20', 'category30', 'town');
$criteria->select = 't.id,business,street,postalCode,contactNo,checkinCount,count(tbl_abc.id) as spcount';
$criteria->join = 'left join tbl_abc on t.id=tbl_abc.businessId';
$criteria->group = 't.id';
$criteria->order = 'spcount DESC';
$criteria->condition='spcount>1';
$bizModel = new CActiveDataProvider(Business::model(), array(
'criteria' => $criteria
));
I'm getting this error:
Column not found: 1054 Unknown column 'spcount' in 'where clause'
If I omit the condition the query works fine & orders businesses by spcount. So how do I rewrite this query such that I get all the businesses whose spcount is greater than 1?
Upvotes: 2
Views: 10444
Reputation: 1
Maybe you could use a sub-select-query.
For example in the select part of you criteria object:
$criteria->select = 't.id,business,street,postalCode,contactNo,checkinCount,(select count(id) from tbl_abc where t.id=businessId) as spcount';
Or as an inner join (which can also contain the "where spcount>1" condition):
$criteria->join = 'join (select businessId, count(*) as spcount from tbl_abc) abc on t.id=abc.businessId and abc.spcount>1';
In both scenarios spcount is also alvailable in the where-clause of your query. Also, "group by t.id" is not necessary anymore since spcount is now a single value for each row of the main table ("t").
Hope this helps
Upvotes: 0
Reputation: 5558
As far as I know, you can't reference aliases in a WHERE
part (proof link). Remove the condition line and add the following:
$criteria->having = 'COUNT(tbl_abc.id) > 1';
UPDATE
CActiveDataProvider
accepts finder instance, so you'll need a model scope:
<?php
class Business extends CActiveRecord
{
public function scopes()
{
return array(
'hasSpcount' => array(
'with' => array('reviewCount', 'category10', 'category20', 'category30', 'town'),
'select' => 't.id,business,street,postalCode,contactNo,checkinCount,count(tbl_abc.id) as spcount',
'join' => 'left join tbl_abc on t.id=tbl_abc.businessId',
'group' => 't.id',
'order' => 'spcount DESC',
'having' => 'COUNT(tbl_abc.id) > 1',
),
);
}
}
// usage
$provider = new CActiveDataProvider(Business::model()->hasSpcount());
Hope this works
Upvotes: 2