我继续为创建对象的 Symfony/Doctrine 方法而苦苦挣扎。目前的问题是如何最好地在一对多的一侧创建一个对象,而不在多侧创建一个对象。问题似乎源于多方面是关系的拥有方,因此是对象是否持久的决定因素。
详细信息:客户实体与成员实体具有一对多的关系。客户端可以自行创建
$client = new Client();
$form = $this->createForm(new ClientType(), $client);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($client);
$em->flush();
return $this->redirect($this->generateUrl('client_show', array('id' => $client->getId())));
}
和一个客户加上一个或多个成员,但不是单独与
$client = new Client();
$member = new Member();
$client->addMember($member);
$form = $this->createForm(new ClientType(), $client);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$member->setClient($client);
$em->persist($member);
$em->flush();
return $this->redirect($this->generateUrl('client_show', array('id' => $client->getId())));
客户实体:
class Client
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Member", mappedBy="client")
*
*/
protected $members;
public function __construct()
{
$this->members = new ArrayCollection();
}
public function getMembers()
{
return $this->members;
}
public function setMembers($members)
{
foreach ($members as $members)
{
$members->addClient($this);
}
$this->members = $members;
return $this;
}
public function addMember(Member $member)
{
$this->members->add($member);
// $member->setClient($this);
return $this;
// $this->members[] = $member;
}
public function removeMember(Member $member)
{
$this->members->removeElement($member);
return $this;
}
会员单位:
class Member
{
/**
* @var integer $id
*
* @ORM\Column(name="hid", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Client",inversedBy="members",cascade={"remove", "persist"})
* @ORM\JoinColumn(name="clientId", referencedColumnName="id")
*
*/
protected $client;
public function setClient(Client $client)
{
$this->client = $client;
return $this;
}
public function getClient()
{
return $this->client;
}
如果没有插入成员,上述代码将引发错误。是否可以使用单个代码来添加具有或不具有成员的客户端?