{"id":738,"date":"2012-02-09T14:58:26","date_gmt":"2012-02-10T00:58:26","guid":{"rendered":"http:\/\/mymonkeydo.com\/?p=738"},"modified":"2012-02-09T14:58:26","modified_gmt":"2012-02-10T00:58:26","slug":"crosswalk-table-with-no-primary-key","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/crosswalk-table-with-no-primary-key\/","title":{"rendered":"Crosswalk Table with No Primary Key"},"content":{"rendered":"
I have a “crosswalk” table like so:<\/p>\n
CREATE table `usergroup` (\n\u00a0 `userId` int NOT NULL DEFAULT '',\n\u00a0 `groupId` int NOT NULL DEFAULT '',\n\u00a0 KEY `userId` (`userId`, `groupId`)\n)<\/pre>\nSo it has no need for a primary key. \u00a0However, when I want to access the table in Yii, like so:<\/p>\n
$user->group->groupName<\/p>\n
I get the following error:<\/p>\n
Invalid argument supplied for foreach()<\/p>\n
on this line:<\/p>\n
foreach($this->_table->primaryKey as $name)<\/pre>\n<\/pre>\nSolution<\/h2>\n
Add a primary key to your AR (model class) like so:<\/p>\n
public function primaryKey() {
\nreturn array(‘userId’, ‘groupId’);
\n}<\/p>\n<\/p>\n