Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii multiple relations to same table

Tags:

model

yii

I have the following relations defined in my UserBan model:

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'),
     );
 }

Now when I try to do:

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

It screams the following because the User mdel has a default scoped relation to 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))

How do I get over this? Where do I "alias" my joined tables ?

EDIT Here is the default scope for the User model:

 public function defaultScope()
     {
         return array(
             'with' => 'nicknames',
             'together' => true
         );
     }
like image 657
Samson Avatar asked Feb 17 '23 12:02

Samson


1 Answers

When you define multiple relations to the same table it's a good idea to specify unique aliases for each one. You do that when specifying the relations:

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'),
 );

See the documentation for CActiveRecord::relations for more information.

Update: It seems you also need to use different aliases for joining the nicknames table in your default scope. I 'm not sure what the best way to do that would be, but this works and it's easy to do:

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

    return array(
        'with' => array(
            'nicknames' => array('alias' => 'nick'.($counter++))
        ),
        'together' => true,
    );
}
like image 199
Jon Avatar answered Apr 28 '23 19:04

Jon