codeigniter doctrine many to many relationships
I have three tables.
User
id
Group
id
UserGroup
user_id
article_id
date_joined
Now I have three separate models to set up the relationship.
// User Model
<?php
class User extends Doctrine_Record
{
// define table columns in this function
public function setTableDefinition() {
}
// setup some options
public function setUp() {
$this->hasMany('Group as Groupss', array(
'local' => 'user_id',
'foreign' => 'group_id',
'refClass' => 'UserGroup'
));
// causes 'created_at' and 'updated_at' fields to be updated automatically
$this->actAs('Timestampable');
}
}
// Group Model
<?php
class Group extends Doctrine_Record
{
// define table columns in this function
public function setTableDefinition() {
}
$this->hasMany('User as Users', array(
'local' => 'group_id',
'foreign' => 'user_id',
'refClass' => 'UserGroup'
));
}
}
/开发者_Python百科/ UserGroups
<?php
class UserGroup extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('user_id', 'integer', 4, array(
'primary' => true
)
);
$this->hasColumn('achievement_id', 'integer', 4, array(
'primary' => true
)
);
$this->hasColumn('date_completed', 'timestamp', 25);
}
}
and now all i want to do is build the relationship inside my controller:
$user = Doctrine::getTable('User')->findOneByEmail('abcd123@gmail.com');
$group = Doctrine::getTable('Group')->findOneByID('1');
$user->Group = $user;
Both SQL commands are returning one result and when I run the controller I get the following error:
Fatal error: Uncaught exception 'Doctrine_Record_UnknownPropertyException' with message 'Unknown record property / related component "User" on "Group"' in
The refclass
option in the User and Group classes should most likely be UserGroup and not UserGroups (Doctrine doesn't understand the difference between singular and plural). You should also invoke the parent::setUp() method in each of the setup() methods you declare.
There's an extensive amount of documentation on many-many relationships in the official manual. (Which uses the user-group relation as an example)
EDIT:
I noticed some severe problems with the code while going through it again:
- Your
UserGroup
table has anarticle_id
column, but nogroup_id
column. - The declared relation to the
Group
model under the nameGroupss
, this making the relation$user->Group
unknown. - Finally, you should assign the user to an array of groups like
$user->Groups[] = $group
精彩评论