Saving embedded collections

两盒软妹~` 提交于 2019-12-11 08:56:22

问题


I have 2 Entities:

Game
Batting

A Game has several other properties, date, location etc A Game has several Batting Entites, i.e a game of cricket A Batting has several properties, Runs, Dismissal, Player

Game.php

 /**
 *
 * @ORM\OneToMany(targetEntity="Batting", mappedBy="game", cascade={"persist", "remove"})
 */
 private $battings;

/**
 * Add battings
 *
 * @param \CW\CricketBundle\Entity\Batting $battings
 * @return Game
 */

public function addBatting(\CW\CricketBundle\Entity\Batting $battings)
{
    $this->battings[] = $battings;

    return $this;
}

Batting.php

 /**
 * @ORM\ManyToOne(targetEntity="CW\CricketBundle\Entity\Game", inversedBy="battings", cascade={"persist"})
 * @ORM\JoinColumn(name="game_id", referencedColumnName="id")
 */
 private $game;

GameAdmin.php

->with("Batting")
  ->add('battings', 'sonata_type_collection', array(), array(
      'edit' => 'inline',
      'inline' => 'table',
      'sortable' => 'id',
  ))

You can see what this like like below

The prblem is when adding a Batting and saving the Game.

I'd expect the game_id to be saved in the batting db table, but its always NULL.

Any ideas what is wrong with my code?

Thanks

EDIT:

Changed code to:

public function addBatting(\CW\CricketBundle\Entity\Batting $battings)
{
    $battings->setGame($this);

    $this->battings[] = $battings;

    return $this;
}

and

public function setGame(\CW\CricketBundle\Entity\Game $game)
{
    $this->game = $game;

    return $this;
}

回答1:


You need to set the game on each of your batting object.

public function addBatting(\CW\CricketBundle\Entity\Batting $battings)
{
    $battings->setGame($this);

    $this->battings[] = $battings;

    return $this;
}



回答2:


Ok, so chnging my admin form class to the following:

        ->add('battings', 'sonata_type_collection',
            array(
                'by_reference' => false
            ),
            array(
                'edit' => 'inline',
                'inline' => 'table',
                'allow_delete' => true
            )
        )

Seemed to work. Now when I save, the game_id is set.



来源:https://stackoverflow.com/questions/19878192/saving-embedded-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!