0

I have a problem with doctrine2 with a simple relationship between the two models Below I have prepared a simple example

/** * @Entity(repositoryClass="PlayerRepository") @Table(name="players") */ class Player { /** * @Id @Column(type="integer") @GeneratedValue */ protected $id; /** * @OneToMany(targetEntity="Wallet", mappedBy="player", cascade={"persist"}) * @var Wallet[] */ private $wallets; public function __construct() { $this->wallets = new ArrayCollection(); } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getWallets() { return $this->wallets; } public function addWallets($wallets) { $this->wallets[] = $wallets; } } 

And second class

/** * @Entity(repositoryClass="WalletRepository") @Table(name="wallets") */ class Wallet { /** * @Id @Column(type="integer") @GeneratedValue */ protected $id; /** * @ManyToOne(targetEntity="Player", inversedBy="wallets") */ private $player; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getPlayer() { return $this->player; } public function setPlayer($player) { $this->player = $player; } } 

For the following code execution, I am not able to add Player object relations to Wallet:

player = new Player(); $player->addWallets(new Wallet); $player->addWallets(new Wallet); $entityManager->persist($player); $entityManager->flush(); 

Maybe it will be better seen in the attached picture: enter image description here

0

1 Answer 1

1

As far as I know you have to set this on the owning site, in this case Wallet, give it a try:

$player = new Player(); $wallet = new Wallet(); $wallet->setPlayer($player); $entityManager->persist($player); $entityManager->persist($wallet); $entityManager->flush(); 
Sign up to request clarification or add additional context in comments.

2 Comments

OK works, but a want assingn many wallets to one player, through Player method addWallets, and Relationships are bidirectional, aren't
I think that won't work, as written in the article I linked in my answer: The owning side of a bidirectional association is the side Doctrine "looks at" when determining the state of the association, and consequently whether there is anything to do to update the association in the database.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.