ManyToOne作为数组(ManyToMany等效)

时间:2018-02-22 15:02:29

标签: php symfony symfony-forms

[设置]

  • Symfony 3.4
  • Forme实体
  • Limon实体(部分来自楼梯)

[PRBLEM]

我有一个Limon可以有不同的形状(Forme)。

问题是,我想使用ManyToMany而不是Forme关系来定义允许的形状(ManyToOne),并将多个id存储为简单数组,因此允许我在创建Forme

时选择允许的形状(Limon

有人可以告诉我应该如何修改我的代码以满足我的需求吗?

的appbundle /实体/ Limon.php

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Forme", inversedBy="limon")
 * @ORM\JoinColumn(nullable=false)
 */
private $forme;

/**
 * Set forme
 *
 * @param \AppBundle\Entity\Forme $forme
 *
 * @return Limon
 */
public function setForme(\AppBundle\Entity\Forme $forme)
{
    $this->forme = $forme;

    return $this;
}

/**
 * Get forme
 *
 * @return \AppBundle\Entity\Forme
 */
public function getForme()
{
    return $this->forme;
}

的appbundle /实体/ Forme.php

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Limon", mappedBy="forme")
 */
private $limon;

/**
 * Constructor
 */
public function __construct() {
    $this->limon=new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Add limon
 *
 * @param \AppBundle\Entity\Limon $limon
 *
 * @return Forme
 */
public function addLimon(\AppBundle\Entity\Limon $limon) {
    $this->limon[]=$limon;

    return $this;
}

/**
 * Remove limon
 *
 * @param \AppBundle\Entity\Limon $limon
 */
public function removeLimon(\AppBundle\Entity\Limon $limon) {
    $this->limon->removeElement($limon);
}

/**
 * Get limon
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getLimon() {
    return $this->limon;
}

的appbundle /形式/ LimonType.php

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('forme', EntityType::class, array(
                'class'=>'AppBundle:Forme',
                'query_builder'=>function(EntityRepository $er) {
                    return $er->createQueryBuilder('f')
                              ->where('f.actif=1');
                },
            ));
}

2 个答案:

答案 0 :(得分:0)

在Symfony 3中,当你想做多对多时,最简单的方法是在两个表之间创建一个表(这里是Lime和Forme)。

示例:

您创建一个表:hasShape ou(aLaForme)

在Lime实体中,您将拥有一系列参考:$ hasShapes:一对多

在Shape实体中,您将拥有一系列参考:$ hasShapes:一对多

在hasShape中,您将引用 Lime的一个对象 $ lime和一个形状对象 $ shape:多对一 < / p>

当您创建Lime时,您将显示一个形状表。

要保存,您必须创建一个对象Lime - &gt;得到这个石灰的ID - &gt;获取所选形状的ID - &gt;将这两个ID保存在hasShape中。

答案 1 :(得分:0)

我认为你应该使用One-To-Many, Unidirectional with Join Table。参考你的代码,它应该是这样的:

AppBundle/Entity/Limon.php

/**
 * Many User have Many Phonenumbers.
 * @ManyToMany(targetEntity="AppBundle\Entity\Forme")
 * @JoinTable(name="lime_form",
 *      joinColumns={@JoinColumn(name="limon_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="form_id", referencedColumnName="id", unique=true)}
 *      )
 */
private $forme;

/**
 * Constructor
 */
public function __construct() {
    $this->limon= new ArrayCollection();
}

这就是全部。上面的代码将生成limon和表格之间的链接表