php - Symfony Doctrine One to Many does not insert foreign key
Solution:
Firstly, you have to understand that Doctrine and Symfony does not work with id's within your entities.In Einsatztag entity, your property should not be called $Buchung_id since it's an instance of buchung and not an id you will find out there.
Moreover, in your loop, you add the Einsatztag to Buchung. But do you process the reverse set ?
I do it this way to always reverse the set/add of entities.
Einsatztag
public function setBuchung(Buchung $pBuchung, $recurs = true){
$this->buchung = $pBuchung;
if($recurs){
$buchung->addEinsatztag($this, false);
}
}
Buchung
public function addEinsatztag(Einsatztag $pEinsatztag, $recurs = true){
$this->einsatztages[] = $pEinsatztag;
if($recurs){
$pEinsatztag->setBuchung($this, false);
}
}
Then, when you will call
$buchung->addEinsatztag($einsatztag);
Or
$einsatztag->set($buchung);
The relation will be set on both side making your FK to be set. Take care of this, you'll have some behavior like double entries if you do not use them properly.
SImplier , you can use default getter/setters and call them on both sides of your relation, using what you already have, like following:
$einsatztag->set($buchung);
$buchung->addEinsatztag($einsatztag);
Hope it helped ;)
Answer
Solution:
First of all, don't use
_id
properties in your code. Let it be$buchung
. If you want it in the database, do it in the annotation. And this also the reason, why it's not working. Your are mapping tobuchung
, but your property is$Buchung_id
You don't have to write the
@JoinColumn
, because<propertyname>_id
would the default column name.Answer
Solution:
I'm going to ignore the naming issue and add a fix to the actual problem.
You need to have in the adder method a call to set the owner.
And to have this adder called when the form is submitted you need to add to the form collection field the
by_reference
property set tofalse
.Here is the documentation:
http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference