0

这里有一篇关于在 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的 insearch()

编辑

根据@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',
                    ),
                    '*',
                ),
            ),
        )
    );
}
4

1 回答 1

2

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

$criteria->with = array(
   'parent'=>array(
      'alias'=>'parent'
    )
);      
于 2012-11-04T17:05:41.290 回答