omg*_*oha 4 php orm doctrine symfony doctrine-orm
几个月前我开始使用symfony,有一件事一直困扰着我.当我在Doctrine中有一对多的关系时,我尝试在数据库中插入一些东西.这是一个例子:
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"]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
然后尝试将其保存到数据库中.
$accountType = new AccountType();
$accountType->setName("blabla");
// additional data to accountType
$broker->addAccountType($accountType);
$em->persist($broker);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
奇怪的是,它只能在一个小问题上正常工作.Broker已更新,AccountType已插入数据库,但accountType与Broker没有任何关系.换句话说,当我在数据库中检查时,broker_id字段重新保持不变并包含NULL.
如果我$accountType->setBroker($broker)手动添加,它可以工作.但是我开始使用Sonata Admin Bundle,这样做要复杂得多,我真的不需要复杂的管理系统.所以我只想快速开发它而没有这个"功能"它几乎是不可能的.
无论如何,如果我将一些东西添加到一个Object的集合中,它应该知道哪个对象是它的父对象,对吧?:)
感谢您的帮助!
class Broker
{
public function addAccountType($accountType)
{
$this->accountTypes[] = $accountType;
// *** This is what you are missing ***
$accountType->setBroker($this);
Run Code Online (Sandbox Code Playgroud)