我有2个与OneToOne关系相关的实体。我将反面嵌入到表单中,一切正常,除了不存储关系之间的链接。 因此:保存“Begeleider”并保存“CompetentieProfiel”,但引用“CompetentieProfiel”表中“Begeleider”的列为空。
当调用flush()时,“Begeleider”对象将“CompetentieProfiel”对象作为变量。
联系人:
class Contact {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
Begeleider:
class Begeleider extends Contact {
/**
* @ORM\OneToOne(targetEntity="CompetentieProfiel", mappedBy="begeleider" ,cascade={"persist"})
*/
private $competentieProfiel;
}
CompetentieProfiel:
class CompetentieProfiel {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="Begeleider", inversedBy="competentieProfiel",cascade={"persist"})
*/
protected $begeleider;
}
形式:
class BegeleiderType extends AbstractType {
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('competentieProfiel', new CompetentieProfielType());
}
控制器:
public function createAction(Request $request) {
$entity = new Begeleider();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
// Return the ok status and the begeleider html.
$response = new Response(
json_encode(
array(
'status' => 'ok',
)
)
);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
答案 0 :(得分:1)
当您从一侧关联对象时,您不是另一侧。所以A与B相关联,但B与A无关,如果这有意义的话。
据我所知,最好的方法是在你的setter中添加一个检查来设置关联对象。
在Aaaa
public function setBbbb(Bbbb $bbbb)
{
if (null === $bbbb->getAaaa() || $this !== $bbbb->getAaaa()) {
$bbbb->setAaaa($this);
}
$this->bbbb = $bbbb;
return $this;
}
在Bbbb
public function setAaaa(Aaaa $aaaa)
{
if (null === $aaaa->getBbbb() || $this !== $aaaa->getBbbb()) {
$aaaa->setBbbb($this);
}
$this->aaaa = $aaaa;
return $this;
}
这样,当设置任何一个边时,另一边也会自动设置。