设置多对多的关系

时间:2011-08-03 08:56:31

标签: php symfony1 doctrine

我有:

  @method Users    setMail()         Sets the current record's "mail" value
  @method Users    setUsersGroups()       Sets the current record's "UsersGroups" collection


   public function save(Doctrine_Connection $conn = null) {

    if($this->isNew()) {

        $this->setMail('test@test.com')); // ok
        $this->setUsersGroups(2);         // doesn't work - error Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.
    }

    parent::save($conn);


}

表用户组:

  user_id
  group_id
这是多对多的关系。

如何为群组设置用户?

示例模式:

Users:
  columns:
    id:
      type: integer(4)
      autoincrement: true
      primary: true
    mail:
      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

UsersGroups:
  columns:
    group_id:
      type: integer(4)
      primary: true
    user_id:
      type: integer(4)
      primary: true
  relations:
    Group:
      foreignAlias: UsersGroups
    Users:
      foreignAlias: UsersGroups

1 个答案:

答案 0 :(得分:1)

   public function save(Doctrine_Connection $conn = null) {

     if($this->isNew()) {

        $this->setMail('test@test.com')); // ok
        parent::save($conn);    

        $ug = new UsersGroups();
        $ug->setUserId($this->getId());
        $ug->setGroupId(2);
        $ug->save();

     } else {
       parent::save($conn);
     }
  }
相关问题