Crosswalk Table with No Primary Key

Problem

I have a “crosswalk” table like so:

CREATE table `usergroup` (
  `userId` int NOT NULL DEFAULT '',
  `groupId` int NOT NULL DEFAULT '',
  KEY `userId` (`userId`, `groupId`)
)

So it has no need for a primary key.  However, when I want to access the table in Yii, like so:

$user->group->groupName

I get the following error:

Invalid argument supplied for foreach()

on this line:

foreach($this->_table->primaryKey as $name)

Solution

Add a primary key to your AR (model class) like so:

public function primaryKey() {
return array(‘userId’, ‘groupId’);
}

 

More info can be found on this forum post:  http://www.yiiframework.com/forum/index.php/topic/12361-yet-model-with-no-primary-key/page__p__60495__hl__primary+key+table#entry60495

Tagged with:

Leave a Reply