我还不能在 Symfony2 中正确配置关联。对于一对多关系(许多家庭成员到一个客户),当前代码显示在下面。
当成员 foreach 循环被省略时,客户端按预期添加。目前的错误是:
通过关系“Mana\ClientBundle\Entity\Client#members”找到了一个新实体,该关系未配置为对实体进行级联持久化操作:Mana\ClientBundle\Entity\Member@00000000248e5b80000000004cc2e70f。要解决这个问题:要么在这个未知实体上显式调用 EntityManager#persist(),要么配置级联在映射中保持此关联,例如 @ManyToOne(..,cascade={"persist"})。如果您无法找出导致问题的实体,请执行“Mana\ClientBundle\Entity\Member#__toString()”以获取线索。
客户端实体片段
namespace Mana\ClientBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Mana\ClientBundle\Entity\Client
*
* @ORM\Table(name="client")
* @ORM\Entity
*/
class Client
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Mana\ClientBundle\Entity\Member", mappedBy="client")
*/
protected $members;
public function __construct()
{
$this->members = new ArrayCollection();
}
public function setMembers(ArrayCollection $members)
{
$this->members = $members;
return $this;
}
public function addMember(Member $member)
{
$this->members->add($member);
return $this;
}
public function removeMember(Member $member)
{
$this->members->removeElement($member);
return $this;
}
public function getMembers()
{
return $this->members;
}
家庭实体
namespace Mana\ClientBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mana\ClientBundle\Entity\Member
*
* @ORM\Table(name="household")
* @ORM\Entity
*/
class Member
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="members")
* @ORM\JoinColumn(name="clientId", referencedColumnName="id")
*
*/
protected $client;
//--- properties
public function setClient(Client $client)
{
$this->client = $client;
return $this;
}
public function getClient()
{
return $this->client;
}
// getters, setters
控制器 createAction():
public function createAction(Request $request)
{
$client = new Client();
$form = $this->createForm(new ClientType(), $client);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($client);
$em->flush();
foreach ($client->getMembers() as $member)
{
$em->persist($member);
}
$em->flush();
return $this->redirect($this->generateUrl('client_show', array('id' => $entity->getId())));
}