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

23
March 16, 2019, at 05:30 AM

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:

Answer 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();
READ ALSO
How to manage complex class dependencies in PHP?

How to manage complex class dependencies in PHP?

I'm writing a PHP script that generates SVG plans for all the components that make up a pinball machine, to send to a laser cutterThere are many dozens of components

31
How can I insert a new column in my table using php and mysql?

How can I insert a new column in my table using php and mysql?

I'm trying to add the column "test" in my table "reservation" but it doesn't work

20
Getting error when trying to edit subpage in Grav

Getting error when trying to edit subpage in Grav

Whenever I try to add or edit a subpage (ie

45
Zend Expressive API does not return contents of objects

Zend Expressive API does not return contents of objects

I'm creating a small API, mostly for learning purposes, but, I might implement it into a project I'm working onSo far, I have installed the zend expressive skeleton application and set up my models and entities

12