当Relation是同一个表中的键时,使用CGridView通过Yii中的相关模型进行搜索和排序

时间:2012-11-04 15:06:07

标签: php yii mysql-error-1066

有一篇关于在CGridView中按相关模型进行搜索和排序的综合文章:http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview/我已多次成功实施此配方。

但是,现在我尝试按同一个表中的关系进行搜索和排序(它定义了parent_id)。请参阅下面的“父母”关系:

public function relations()
{
    return array(
        'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
        'children' => array(self::HAS_MANY, 'Category', 'parent_id'),
        'childCount' => array(self::STAT, 'Category', 'parent_id'),
        'author0' => array(self::BELONGS_TO, 'User', 'author'),
        'contents' => array(self::MANY_MANY, 'Content', 'content_category(content_id, category_id)'),
        'crsContents' => array(self::MANY_MANY, 'ContentCrs', 'content_category(content_id, category_id)'),
    );
}

public function defaultScope()
{
    return array(
        'alias'=>'cat',
        'order'=>"cat.name ASC",
    );
}

当我实现wiki指定的方法时,我收到以下错误:

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'cat'. The SQL statement executed was: SELECT COUNT(DISTINCT `cat`.`id`) FROM `category` `cat` LEFT OUTER JOIN `category` `cat` ON (`cat`.`parent_id`=`cat`.`id`) WHERE (cat.parent_id <> 257)

如何确保LEFT OUTER JOIN为关系使用唯一的表别名(例如parent),以便我可以在CDbCriteria中正确定义search()

修改

根据@tereško的要求,这是我的search()函数。我知道它是有缺陷的,因为我没有定义它时指定的表别名parent ...我只是不知道如何!

public function search()
{
    $criteria=new CDbCriteria;
    $criteria->with = array('parent');

    $criteria->compare('id',$this->id,true);
    $criteria->compare('author',$this->author,true);
    $criteria->compare('name',$this->name,true);
    $criteria->compare('description',$this->description,true);
    $criteria->compare('parent_id',$this->parent_id,true);
    $criteria->compare('parent.name', $this->parent_search, true );
    $criteria->compare('type',$this->type,true);
    $criteria->compare('slug',$this->slug,true);
    $criteria->compare('created',$this->created,true);
    $criteria->compare('updated',$this->updated,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
            'sort'=>array(
                'attributes'=>array(
                    'parent_search'=>array(
                        'asc'=>'parent.name',
                        'desc'=>'parent.name DESC',
                    ),
                    '*',
                ),
            ),
        )
    );
}

1 个答案:

答案 0 :(得分:2)

您可以为父关系提供别名,如下所示

$criteria->with = array(
   'parent'=>array(
      'alias'=>'parent'
    )
);