2013-10-26 61 views
3

几个月前我开始与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,这样做更加复杂,我并不需要复杂的管理系统。所以我只想快速开发它,如果没有这个“功能”,这几乎是不可能的。

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

感谢您的帮助提前!

+0

在添加'$ accountType'之前,您的Broker对象'$ broker'是否已由doctrine知道(即从存储库中获取)? – nifr

+0

如果您在使用setter添加到代理之前坚持新创建的$ accountType,会发生什么情况? $ EM->坚持($ ACCOUNTTYPE); – busypeoples

+0

这就是级联选项基本上是 - 他不想明确坚持相关的实体。 – nifr

回答

5
class Broker 
{ 
    public function addAccountType($accountType) 
    { 
     $this->accountTypes[] = $accountType; 

     // *** This is what you are missing *** 
     $accountType->setBroker($this); 
+0

谢谢!我用教义生成了实体类,我没有想到在模型类中的这个小小的改变。 (也许这在教条中有一个选项呢?这对我来说似乎是一个很常见的交易。) – omgitsdrobinoha

+1

还有一件事,当我测试它的时候,它就像我在我的问题中写的那样。但是当我向集合中添加某些内容时,它在Sonata Admin捆绑软件中不起作用。 :(( – omgitsdrobinoha