4

我的UserBan模型中定义了以下关系:

public function relations()
 {
     // NOTE: you may need to adjust the relation name and the related
     // class name for the relations automatically generated below.
     return array(
         'user' => array(self::BELONGS_TO, 'User', 'userId'),
         'target' => array(self::BELONGS_TO, 'User', 'targetId'),
         'author' => array(self::BELONGS_TO, 'User', 'authorId'),
     );
 }

现在,当我尝试这样做时:

$criteria->with = array('user', 'target');

它尖叫如下,因为 User mdel 与 Nicknames 具有默认范围关系:

Not unique table/alias: 'nicknames'

SQL:

    SELECT COUNT(DISTINCT `t`.`id`) FROM `userban` `t` 
LEFT OUTER JOIN `user` `user` ON (`t`.`userId`=`user`.`id`) 
LEFT OUTER JOIN `nickname` `nicknames` ON (`nicknames`.`userId`=`user`.`id`) 
LEFT OUTER JOIN `user` `target` ON (`t`.`targetId`=`target`.`id`) 
LEFT OUTER JOIN `nickname` `nicknames` ON (`nicknames`.`userId`=`target`.`id`) 
WHERE ((user.name LIKE :username) AND (:dateStart<=t.createdAt AND :dateEnd>=t.createdAt))

我该如何克服呢?我在哪里“别名”我的连接表?

编辑这是用户模型的默认范围:

 public function defaultScope()
     {
         return array(
             'with' => 'nicknames',
             'together' => true
         );
     }
4

1 回答 1

8

当您为同一个表定义多个关系时,最好为每个关系指定唯一的别名。您在指定关系时这样做:

return array(
     'user' => array(self::BELONGS_TO, 'User', 'userId', 'alias' => 'unick'),
     'target' => array(self::BELONGS_TO, 'User', 'targetId', 'alias' => 'tnick'),
     'author' => array(self::BELONGS_TO, 'User', 'authorId', 'alias' => 'anick'),
 );

CActiveRecord::relations有关更多信息,请参阅文档。

更新:您似乎还需要使用不同的别名来加入nicknames默认范围内的表。我不确定最好的方法是什么,但这很有效,而且很容易做到:

public function defaultScope()
{
    static $counter = 0;

    return array(
        'with' => array(
            'nicknames' => array('alias' => 'nick'.($counter++))
        ),
        'together' => true,
    );
}
于 2013-05-20T10:27:47.620 回答