有没有办法在关系中正确保存ManyToMany字段实体的形式是“多个”并且是集合的一部分? 我到处寻找,但找不到一丝例子让我明白该怎么做!
我无法找到解决方案!
class Anagrafica
{
/**
* @ORM\ManyToMany(targetEntity="SubCategories", inversedBy="anagrafiche", cascade={"persist", "remove"})
* @ORM\JoinTable(name="AnCat")
**/
private $subCategories;
//..
public function __construct()
{
$this->subCategories = new \Doctrine\Common\Collections\ArrayCollection();
//..
}
/**
* Add subCategories
*
* @param \My\BusinessBundle\Entity\SubCategories $subCategories
* @return Anagrafica
*/
public function addSubCategory(\My\BusinessBundle\Entity\SubCategories $subCategories)
{
foreach ($subCategories as $subCategory) {
$subCategory->addAnagrafiche($this);
}
$this->subCategories = $subCategories;
}
*******
class SubCategories
{
/**
* @ORM\ManyToMany(targetEntity="Anagrafica", mappedBy="subCategories")
*/
private $anagrafiche;
public function __construct()
{
$this->anagrafiche = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add anagrafiche
*
* @param \My\BusinessBundle\Entity\Anagrafica $anagrafiche
* @return SubCategories
*/
public function addAnagrafiche(\My\BusinessBundle\Entity\Anagrafica $anagrafiche)
{
if (!$this->anagrafiche->contains($anagrafiche)) {
$this->anagrafiche->add($anagrafiche);
}
}
******
AnagraficaType:
//..
->add('subCategories', 'collection', array('type' => new SubCategoriesType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__categ__',
'by_reference' => false
))
*******
SubCategoriesType:
->add('subCategory', 'entity', array(
'class' => 'CoffeeBusinessBundle:SubCategories',
'property' => 'subCategory',
'label' => 'Sotto Categorie',
'multiple' => true
))
答案 0 :(得分:0)
如果我直接输入字段集并执行以下更改:
AnagraficaType:
->add('subCategories', 'collection', array(
'type' => 'entity',
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__categ__',
'by_reference' => false,
'options' => array(
'label' => 'Sotto Categorie',
'multiple' => true,
'class' => 'MyBusinessBundle:SubCategories',
'property' => 'subCategory'
)
))
Anagrafica实体:
public function addSubCategory(ArrayCollection $subCategories)
{
foreach ($subCategories as $subCategory) {
$subCategory->addAnagrafiche($this);
//var_dump($subCategory);
}
$this->subCategories = $subCategories;
}
部分获得所需的结果,但如果我在表单子类别中添加一个字段(按集合),则只保存输入的最后一个字段。 我收到了一个var_dump ArrayCollection对象,实际上里面只有输入的最后一个字段的数据。
有什么想法吗?