2

有没有办法以“多个”并且是集合的一部分的形式正确保存在关系 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
    ))
4

1 回答 1

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 对象,实际上里面只有最后一个输入字段的数据。

任何的想法?

于 2013-03-01T16:50:26.883 回答