Symfony学说中的许多关系

问题描述 投票:0回答:1

我有一个代理商实体,其字段是$ owns

好像

      /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\ShipType", inversedBy="owners")
     */
    protected $owns;

在ShipType实体我有

/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Agency", mappedBy="owns")
 */
private $owners;

doctrine为使用agency_id和ship_type_id的表之间的关联创建了一个关系表

我正在尝试获得一个表格,以便将每个机构分配给一种船型(拥有)我试图实现作为代理商的记录

到目前为止我得到了

   public function gShips(Request $request): Response {
    $u = $this->getUser();
    $ag = new Agency();
    $form = $this->createForm(ChooseShipsType::class, $ag);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $a = $form->getData();
        $em->persist($a);
        $em->flush();

    }

    return $this->render('agency/sships.html.twig', [
        'adForm' => $form->createView()
    ]);
}

和形式

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('ships', EntityType::class, [
            'class' => 'AppBundle:ShipType',
            'expanded'  => true,
            'multiple'  => true,
        ])
        ->add('save', SubmitType::class)
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => 'AppBundle\Entity\Agency'
    ]);
}

表单正在显示,但无法让它继续存在,因为它正在尝试创建一个新的代理,我无法弄清楚如何使用这两个表之间的关系表

先感谢您

php symfony doctrine-orm
1个回答
1
投票

检查您的Agency类的构造函数。确保它具有以下内容:

$this->owns = new ArrayCollection();

然后,确保你有一个addOwns()方法:

public function addOwns(ShipType $shipType) 
{
    $this->owns[] = $shipType;
}

还有一个二传手:

public function setOwns($owns)
{
    if ($owns instanceof ArrayCollection) {
        $this->owns = $owns;
    } else {
        if (!$this->owns->contains($owns)) {
            $this->owns[] = $owns;
        }
        $this->owns;
    }
    return $this;
}

此外,请确保您拥有默认内容的getter。那应该做。

PS:你不应该把你的属性命名为动词,但这是另一回事。

© www.soinside.com 2019 - 2024. All rights reserved.