几个月前我开始与symfony一起工作,有一件事情一直在困扰着我。当我在Doctrine中拥有一对多的关系时,我试图在数据库中插入一些东西。这里有一个例子:级联坚持不工作(学说ORM + Symfony 2)
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();
奇怪的是,它只有一个很小的问题,工作prefrectly。代理已更新,并且AccountType已插入到数据库中,但该帐户类型与代理没有任何关系。换句话说,当我检查数据库时,broker_id
字段保持不变,并且包含NULL
。
如果我手动添加$accountType->setBroker($broker)
,它可以工作。但是我开始使用Sonata Admin Bundle,这样做更加复杂,我并不需要复杂的管理系统。所以我只想快速开发它,如果没有这个“功能”,这几乎是不可能的。
无论如何,如果我添加一些东西到一个对象的集合,它应该知道哪个对象是它的父对象,对吧? :)
感谢您的帮助提前!
在添加'$ accountType'之前,您的Broker对象'$ broker'是否已由doctrine知道(即从存储库中获取)? – nifr
如果您在使用setter添加到代理之前坚持新创建的$ accountType,会发生什么情况? $ EM->坚持($ ACCOUNTTYPE); – busypeoples
这就是级联选项基本上是 - 他不想明确坚持相关的实体。 – nifr