Reputation: 7935
I have two tables, game
and own
. In own
's entity I have created OneToMany
relationship:
/** @ORM\ManyToOne(targetEntity="Game") */
private $game;
And in game
Entity field id
is also mapped:
* @ORM\OneToMany(targetEntity="Own", mappedBy="game")
Now I have a problem with inserting new data in my database. I tried simply persisting objects:
$gameown = new Own();
$gameown -> setGame('3');
$gameown -> setUpdated(date("Y-m-d H:i:s"));
$em = $this->getDoctrine()->getEntityManager();
$em->persist($gameown);
$em->flush();
But it doesn't work. Symfony is saying that it must be an Game
instance, not a string. How to solve this?
When I try this:
$gameown -> setGame($game->getId('3'));
It insert okay, but... null values.
Upvotes: 0
Views: 1655
Reputation: 31548
Or
You can do this way as well
$gameObject = $em->getRepository('YourBundle:Game')->findOneBy(array('id' => 3));
Then you can use
$gameown->setGame($gameObject);
Upvotes: 2
Reputation: 4704
Actually, you have to use a game object, and doctrine will do the work for you. Think with object, not with table.
First, you have to retrieve your objects (from the database for example) :
$em = $this->getDoctrine()->getEntityManager();
$game = $em->getRepository('AppMonBundle:Game')->find(3);
Then, you can set the relation :
$gameown->setGame($game);
Upvotes: 1