实体用户
class User {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
...
/**
* @ORM\ManyToMany(targetEntity="Controleitor\Model\Entity\Account", mappedBy="user")
*/
protected $userAccount;
public function __construct() {
$this->userAccount = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getUserAccount() {
return $this->userAccount;
}
...
}
实体账户
class Account{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
*
* @ORM\ManyToMany(targetEntity="JasUser\Model\Entity\User", inversedBy="userAccount")
* @ORM\JoinTable(name="user_has_account",
* joinColumns={@ORM\JoinColumn(name="idAccount", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="idUser", referencedColumnName="id")}
* )
*/
private $user;
public function __construct(array $options = null) {
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
...
}
测试:
$user = $this->entityManager->getRepository('User')->findOneById($id);
$user->getUserAccount()->add($account);
$this->entityManager->persist($account);
$this->entityManager->flush();
$id = $entity->getId();
它获取用户、userAccount 并在数据库中插入新记录帐户,但它没有像我期望的那样使用 add 方法在 user_has_account 表中添加用户和帐户之间的多对多关联的记录。