I started working with symfony several months ago and there is one thing keeps bothering me all the time. It is when I have a one-to-many relationship in Doctrine and I try to insert something into the database. Here's an example:
Broker.orm.yml
Acme\DemoBundle\Entity\Broker:
type: entity
table: brokers
repositoryClass: BrokerRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 255
slug:
type: string
length: 64
oneToMany:
accountTypes:
targetEntity: Acme\DemoBundle\Entity\AccountType
mappedBy: broker
cascade: ["persist"]
AccountType.orm.yml
Acme\DemoBundle\Entity\AccountType:
type: entity
table: account_types
repositoryClass: AccountTypeRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 255
slug:
type: string
length: 64
manyToOne:
broker:
targetEntity: Acme\DemoBundle\Entity\Broker
inversedBy: accountTypes
joinColumn:
name: broker_id
referencedColumn: id
Then is try to save it to the database like this.
$accountType = new AccountType();
$accountType->setName("blabla");
// additional data to accountType
$broker->addAccountType($accountType);
$em->persist($broker);
$em->flush();
The strange thing is that it works prefrectly with only one tiny problem. Broker is updated, and AccountType is inserted into the database but the accountType doesn't have any relations with the Broker. In other words, when I check in the database the broker_id
fields reamains untouched and contains NULL
.
If I add $accountType->setBroker($broker)
manually, it works. But I started to use Sonata Admin Bundle where there is much more complicated to do this and I don't really need a complex admin system. So I just want a fast development on it and without this "feature" it's nearly impossible.
And anyways, if I add something to a collection of an Object, it should know which object is its parent, right? :)
Thanks for your help in advance!