问题
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