简体   繁体   English

交往学说中的多对多关系

[英]ManyToMany relations in symfony doctrine

i have a Agency Entity with a fields $owns 我有一个具有$ owns字段的代理商实体

looks like 看起来像

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

on ShipType Entity i have 在我拥有的ShipType实体上

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

doctrine created a relations table for association between tables with agency_id and ship_type_id 原则创建了一个关系表,用于具有agency_id和ship_type_id的表之间的关联

i'm trying to get a form to work for assign each agency to a ship type ( owns ) im trying to achieve logging as an agency 我正在尝试获取一份表格,以将每个代理分配给一个船型(拥有),我试图以代理的身份登录

so far i got 到目前为止,我得到了

   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()
    ]);
}

and the form 和形式

 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'
    ]);
}

the form is showing, but can't get it to persist because it's trying to create a new Agency, i can't figure out how to use the relation table between these two tables 表单正在显示,但由于要创建新的代理机构而无法使其持久化,我无法弄清楚如何使用这两个表之间的关系表

thank you in advance 先感谢您

Check the constructor of your Agency class. 检查您的Agency类的构造函数。 Make sure it has the following: 确保它具有以下内容:

$this->owns = new ArrayCollection();

And then, make sure you have an addOwns() method: 然后,确保您具有addOwns()方法:

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

And also a setter: 还有一个二传手:

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

Also, make sure you have the getter with the default content. 另外,请确保您具有带有默认内容的吸气剂。 That should do. 那应该做。

PS: You shouldn't name your properties as verbs though, but that's another thing. PS:虽然您不应该将属性命名为动词,但这是另一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM