开发者

Doctrine 2 Can't Seem to Remove Many to Many Relationships

开发者 https://www.devze.com 2023-02-01 23:51 出处:网络
I have the following setup \"Many Users can have Many Projects (Collaborators)\" /** * @Entity @HasLifeCycleCallbacks

I have the following setup "Many Users can have Many Projects (Collaborators)"

/**
 * @Entity @HasLifeCycleCallbacks
 * @Table(name="projects")
 */
class Project implements \Zend_Acl_Resource_Interface {
  /**
   * @ManyToMany(targetEntity="User", mappedBy="projects")
   * @OrderBy({"displayName" = "ASC", "username" = "ASC"})
   */
  protected $collaborators;

  ..
}

/**
 * @Entity 
 * @Table(name="users")
 */
class User implements \Zend_Acl_Role_Interface {
  /**
   * @ManyToMany(targetEntity="Project", inversedBy="collaborators")
   */
  protected $projects;
  ...
}

I tried to remove a collaborator using the following

$user = Application_DAO_User::findById($this->_getParam('userid'));
$proj = Application_DAO_Project::getProjectById($this->_getParam('id'));
Application_DAO_Project::removeCollaborator($proj, $user); // <---

// Application_DAO_User
public static function findById($id) {
  return self::getStaticEm()->find('Application\Models\User', $id);
}

// Application_DAO_Project
public static function getProjectById($id) {
  return self::getStaticEm()->find('Application\Models\P开发者_高级运维roject', $id);
}

public static function removeCollaborator(Project $proj, User $collaborator) { // <---
  $proj->getCollaborators()->remove($collaborator);
  $collaborator->getProjects()->remove($proj);
  self::getStaticEm()->flush();
}

And there isn't any errors but the database stays the same ...


This may be well over due but was just experiencing the same problem myself... According to the doctrine 2 documents, the function ArrayCollection->remove($i) is for removing by array index.

What you are after is:

getCollaborators()->removeElement($collaborator);


I went round in circles trying to figure this out until I realised that for this to work:

getCollaborators()->removeElement($collaborator);

$collaborator would have to be the actual object from the collaborators ArrayCollection. That is, if you pass in a new Collaborator object with the same parameters it won't remove it. That's because ArrayCollection uses array_search to look for the object you want to remove.

Hope that saves someone else a few hours...

0

精彩评论

暂无评论...
验证码 换一张
取 消