几个月前我开始使用 symfony,有一件事一直困扰着我。当我在 Doctrine 中有一个一对多的关系时,我试图向数据库中插入一些东西。这是一个例子:
经纪人.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 没有任何关系。 换句话说,当我在数据库中 checkin broker_id
字段保持不变并包含 NULL
。
如果我手动添加 $accountType->setBroker($broker)
,它会起作用。但是我开始使用 Sonata Admin Bundle,因为这样做要复杂得多,而且我真的不需要复杂的管理系统。所以我只想快速开发它,没有这个“功能”,这几乎是不可能的。
无论如何,如果我向一个对象的集合中添加一些东西,它应该知道哪个对象是它的父对象,对吧? :)
提前感谢您的帮助!
最佳答案
class Broker
{
public function addAccountType($accountType)
{
$this->accountTypes[] = $accountType;
// *** This is what you are missing ***
$accountType->setBroker($this);
关于php - 级联坚持不工作(Doctrine ORM + Symfony 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19605578/