简体   繁体   English

Symfony 3形式和一对多

[英]Symfony 3 form and one-to-many

This seems to be an easy task, but I can't figure out the best solution. 这似乎是一项容易的任务,但是我找不到最佳的解决方案。 I have bidirectional one-to-many relation between trainer and teams (one trainer can have many teams). 我在教练和团队之间存在一对多的双向关系(一个教练可以有很多团队)。 When I add / edit a trainer I want to assign him team/teams. 当我添加/编辑教练时,我想分配他的团队。 I got no error, but nothing happens. 我没有错误,但是什么也没发生。 My guess is that this has something to do with the relation, owning side or something similar. 我的猜测是,这与关系,拥有方面或类似方面有关。 There's another relation: players - team and everything works fine, but in this case I have a player form and I assign team to a player. 还有另一种关系:球员-球队,一切都很好,但是在这种情况下,我有一个球员表格,我将球队分配给一个球员。

So if I submit a form from "many" perspective, it works, but when I try to do it from "one" persepctive, I still get null in db and relation is not being established. 因此,如果我从“许多”的角度提交表单,则可以使用,但是当我尝试从“一个”的角度提交表单时,我在db中仍然为null,并且未建立关系。

Trainer.php: Trainer.php:

/**
* @ORM\OneToMany(targetEntity="Team", mappedBy="trainer")
*/
private $teams;
...
$this->teams = new ArrayCollection();

Team.php: Team.php:

/**
 * @ORM\ManyToOne(targetEntity="Trainer", inversedBy="teams")
 * @ORM\JoinColumn(name="trainer_id", referencedColumnName="id")
 */
private $trainer;

TrainerType.php: TrainerType.php:

        ->add('teams', EntityType::class, array(
            'class' => 'AppBundle:Team',
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true,
            'label' => 'Teams',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('t')
                    ->where('t.isMyTeam = 1')    
                    ->orderBy('t.name', 'ASC');
            },              
        )); 

Is there a way to make it work with one to many relation? 有没有办法使它与一对多关系一起工作? Or should I switch to many-to-many? 还是我应该切换到多对多?

Indeed it is connected with owning side and inverse side. 实际上,它与拥有侧和反向侧相关。 If you add relation as the owning side it will work but not the other way. 如果将关系添加为拥有方,它将起作用,但反之则不行。 Read this in Doctrine documentation and this about owning side . 阅读Doctrine文档中的这个以及关于拥有方的这个。

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

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