级联持久不起作用(Doctrine ORM + Symfony 2)


Cascaded persist not working (Doctrine ORM + Symfony 2)

几个月前我开始使用symfony,有一件事一直困扰着我。当我在教义中有一个一对多的关系,我试图将一些东西插入数据库时。下面是一个示例:

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_id字段保持不变并包含NULL

如果我手动添加$accountType->setBroker($broker),它可以工作。但是我开始使用Sonata管理捆绑包,这样做要复杂得多,而且我真的不需要复杂的管理系统。所以我只想快速开发它,没有这个"功能",这几乎是不可能的。

无论如何,如果我向 Object 的集合添加一些东西,它应该知道哪个对象是它的父对象,对吧? :)

提前感谢您的帮助!

class Broker
{
    public function addAccountType($accountType)
    {
        $this->accountTypes[] = $accountType;
        // *** This is what you are missing ***
        $accountType->setBroker($this);