条件在yii框架php的标准

时间:2012-03-23 13:23:27

标签: php mysql yii

$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
));

我收到了这个错误:

Column not found: 1054 Unknown column 'spcount' in 'where clause'

如果我省略条件,查询工作正常&通过spcount订购业务。那么如何重写这个查询,以便我获得spcount大于1的所有业务?

2 个答案:

答案 0 :(得分:2)

据我所知,您无法在WHERE部分(proof link)中引用别名。删除条件行并添加以下内容:

$criteria->having = 'COUNT(tbl_abc.id) > 1';

<强>更新

CActiveDataProvider accepts finder instance,因此您需要一个模型范围:

<?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());

希望这有效

答案 1 :(得分:0)

也许您可以使用子选择查询。

例如,在标准对象的选择部分中:

$criteria->select = 't.id,business,street,postalCode,contactNo,checkinCount,(select count(id) from tbl_abc where t.id=businessId) as spcount';

或者作为内部联接(也可以包含&#34;其中spcount&gt; 1&#34;条件):

$criteria->join = 'join (select businessId, count(*) as spcount from tbl_abc) abc on t.id=abc.businessId and abc.spcount>1';

在这两种情况下,spcount也可以在查询的where子句中使用。此外,&#34;分组由t.id&#34;因为spcount现在是主表的每一行的单个值(&#34; t&#34;),所以不再需要了。

希望这有帮助