我刚刚创建了一个具有多对多关系(用户组)和下面代码的新项目。
正如你可以在代码中猜到的那样,我试图手动将组分配给用户,但它没有任何分配...任何想法?
User:
columns:
id:
type: integer(4)
autoincrement: true
primary: true
username:
type: string(255)
password:
type: string(255)
attributes:
export: all
validate: true
Group:
tableName: group_table
columns:
id:
type: integer(4)
autoincrement: true
primary: true
name:
type: string(255)
relations:
Users:
foreignAlias: Groups
class: User
refClass: GroupUser
GroupUser:
columns:
group_id:
type: integer(4)
primary: true
user_id:
type: integer(4)
primary: true
relations:
Group:
foreignAlias: GroupUsers
User:
foreignAlias: GroupUsers
代码是这样的:
public function executeIndex(sfWebRequest $request)
{
$user = Doctrine_Core::getTable('User')->find(1);
$groups = Doctrine_Core::getTable('Group')->findAll();
$user->setGroups($groups);
$user->save();
$this->forward('default', 'module');
}
答案 0 :(得分:2)
尝试在User实体中定义关系(并且不要在Groups中使用foreingAlias)。还可以使用本地和外部字段。 因此,schema.yml应该如下所示:
User:
...
relations:
Groups:
class: Group
refClass: GroupUser
local: user_id
foreign: group_id
Group:
...
relations:
Users:
class: User
refClass: GroupUser
local: group_id
foreign: user_id
如果这不起作用,我认为您可以使用Doctrine“link”方法设置组。 请参阅Record.php(可能在lib / vendor / symfony / lib / plugins / sfDoctrinePlugin / lib / vendor / doctrine / Doctrine文件夹中)
示例:
$groups_ids = array();
foreach($groups as $group) $groups_ids[] = $group->getId();
$user->link('Groups',$groups_ids);
此外,如果您只是尝试向该关系添加实例(并且您讨厌将来修复代码的人),您可以创建N-GroupUsers 例如:
foreach($groups as $group) {
$ug = new GroupUser();
$ug->setUserId($user->getId());
$ug->setGroupId($user->getId());
$ug->save();
}
请使用第一个选项,如果有任何问题,请告诉我们!