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
然后尝试将其保存到数据库中。
$accountType = new AccountType();
$accountType->setName("blabla");
// additional data to accountType
$broker->addAccountType($accountType);
$em->persist($broker);
$em->flush();
奇怪的是,它只能在一个小问题上正常工作。 Broker已更新,并且AccountType已插入数据库,但 accountType与Broker没有任何关系。换句话说,当我在数据库中签入时,broker_id
字段未被触及并包含NULL
。
如果我手动添加$accountType->setBroker($broker)
,则可以。但是我开始使用Sonata Admin Bundle,这样做要复杂得多,我真的不需要复杂的管理系统。所以我只想快速开发它而没有这个“功能”几乎是不可能的。
无论如何,如果我将一些东西添加到一个Object的集合中,它应该知道哪个对象是它的父对象,对吧? :)
提前感谢您的帮助!
答案 0 :(得分:5)
class Broker
{
public function addAccountType($accountType)
{
$this->accountTypes[] = $accountType;
// *** This is what you are missing ***
$accountType->setBroker($this);