2

我刚刚创建了一个具有多对多关系(用户组)和以下代码的新项目。

正如您可以在代码中猜到的那样,我正在尝试将组手动分配给用户,但它没有分配任何东西......任何想法?

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

1 回答 1

2

尝试在用户实体中定义关系(并且不要在组中使用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“链接”方法设置组。查看 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();
}

请使用第一个选项,让我知道这是否适合您!

于 2012-06-19T19:57:28.100 回答