Customer
是“关键字/客户”关系的反面,与 Keyword
:
/**
* @ORM\ManyToMany(targetEntity="Keyword", mappedBy="customers",
* cascade={"persist", "remove"}
* )
*/
protected $keywords;
创建新客户时,应选择一个或多个关键字。实体表单字段为:
$form->add($this->factory->createNamed('entity', 'keywords', null, array(
'class' => 'Acme\HelloBundle\Entity\Keyword',
'property' => 'select_label',
'multiple' => true,
'expanded' => true,
)));
在我的 Controller 代码中,绑定(bind)请求并检查表单是否有效后,我需要保留客户和所有客户/关键字关联,即连接表。
但是客户是反面,所以这是行不通的:
if($request->isPost()) {
$form->bindRequest($request);
if(!$form->isValid()) {
return array('form' => $form->createView());
}
// Valid form here
$em = $this->getEntityManager();
$em->persist($customer);
$em->flush();
}
带有“级联”选项的事件,此代码失败。
$customer->getKeywords()
将返回 Doctrine\ORM\PersistentCollection
,其中仅包含选定的关键字。我是否应该手动检查删除/添加了哪个关键字,然后从拥有方更新?
最佳答案
好的,找到了方法,即使我并不完全满意。关键是this example表单集合字段类型。基本上,我之前的表单定义发生的情况是:
$customer->getKeywords() = $postData; // $postData is somewhere in form framework
这只是将(选定关键字的)集合分配给客户关键字。
Keyword
上没有调用任何方法实例(拥有方)。关键选项是by_reference
(对我来说这只是一个坏名字,但无论如何......):$form
->add($this->factory->createNamed('entity', 'keywords', null, array(
// ...
'by_reference' => false
))
);
这样表单框架将调用setter,即
$customer->setKeywords(Collection $keywords)
.在该方法中,您可以“告诉”拥有方存储您的关联:public function setKeywords(Collection $keywords)
{
foreach($keywords as $keyword) {
$keyword->addCustomer($this); // Owning side call!
}
$this->keywords = $keywords;
return $this;
}
(始终使用
contains
方法检查拥有方的重复实例)。此时,只会添加选中的关键字(
$keyword
参数)。需要管理删除未经检查的关键字( Controller 端):$originalKeywords = $customer->getKeywords()->toArray(); // When GET or POST
// When POST and form valid
$checkedKeywords = $customer->getKeywords()->toArray(); // Thanks to setKeywords
// Loop over all keywords
foreach($originalKeywords as $keyword) {
if(!in_array($keyword, $checkedKeywords)) { // Keyword has been unchecked
$keyword->removeCustomer($customer);
$manager->persist($keyword);
}
}
丑陋,但有效。我会将删除代码移至
Customer
类,但根本不可能。如果您能找到更好的解决方案,请告诉我!
关于symfony - 在 Doctrine 2 中更新(从反面)双向多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13426653/