Costy
Costy

Reputation: 165

Doctrine2 - No foreign key inserted in the table with relation OneToMany(

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

Upvotes: 0

Views: 51

Answers (1)

Fabian Schmick
Fabian Schmick

Reputation: 1654

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

Upvotes: 1

Related Questions