尝试保持一对多关系时出错。 特别是,一个客户可能有多个家庭成员;一个给定的家庭成员与一个且只有一个客户相关联。 [我是Symfony的新手,所以会出现错误! 感谢您的指导。
注意:下面的备用控制器代码段通过尝试将家庭表中的客户端 ID 设置为 null 来产生完整性约束错误。
客户端实体代码段
namespace ManaAdminBundleEntity;
use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;
/**
* ManaAdminBundleEntityClients
*
* @ORMTable(name="clients")
* @ORMEntity
*/
class Clients
{
protected $members;
public function __construct()
{
$this->members = new ArrayCollection();
}
public function getMembers()
{
return $this->members;
}
public function setMembers(ArrayCollection $members)
{
$this->members = $members;
}
/**
* @var integer $id
*
* @ORMColumn(name="id", type="integer", nullable=false)
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
* @ORMOneToMany(targetEntity="Household", mappedBy="clients")
* @ORMManyToOne(targetEntity="EthDesc", inversedBy="clients")
* @ORMJoinColumn(name="eid", referencedColumnName="id")
*/
家庭实体代码段
namespace ManaAdminBundleEntity;
use DoctrineORMMapping as ORM;
/**
* ManaAdminBundleEntityHousehold
*
* @ORMTable(name="household")
* @ORMEntity(repositoryClass="ManaAdminBundleEntityHouseholdRepository")
*/
class Household {
/**
* @var integer $hid
*
* @ORMColumn(name="hid", type="integer", nullable=false)
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
* @ORMManyToOne(targetEntity="Clients", inversedBy="members")
* @ORMJoinColumn(name="cid", referencedColumnName="id")
* @ORMManyToOne(targetEntity="EthDesc", inversedBy="members")
* @ORMJoinColumn(name="eid", referencedColumnName="id")
*/
客户端类型代码段
->add('members', 'collection', array(
'type' => new HouseholdType(),
'allow_add' => true,
'by_reference' => false,
'cascade_validation' => true,
));
控制器代码段
public function createAction(Request $request) {
$entity = new Clients();
$form = $this->createForm(new ClientsType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->persist($entity->getMembers());
$em->flush();
return $this->redirect($this->generateUrl('clients_show', array('id' => $entity->getId())));
}
}
备用控制器代码段
public function createAction(Request $request) {
$entity = new Clients();
$form = $this->createForm(new ClientsType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
foreach ($entity->getMembers() as $member)
{
$em->persist($member);
}
$em->flush();
return $this->redirect($this->generateUrl('clients_show', array('id' => $entity->getId())));
}
我让这个工作的时候,我没有
use DoctrineCommonCollectionsArrayCollection;
我只是
$this->field = new DoctrineCommonCollectionsArrayCollection();
在我的构造函数中。
此外,您可能需要考虑将 Family(似乎是客户端中的成员)添加为实体窗体:
->add('members', 'entity', array(
'type' => new HouseholdType(),
'allow_add' => true,
'by_reference' => false,
));
就我而言,我(错误地)试图访问ToMany关系,因为它是ToOne关系(类似于这个答案)。