Doctrine2 lifecycleCallbacks prePersist没有使用YAML配置触发

时间:2011-10-05 19:11:08

标签: doctrine-orm symfony persist

我的所有Doctrine2设置都在YAML文件中完成。我有一个名为LoanAppMenuProgress的实体类,我正在尝试执行prePersist函数。此LoanAppMenuProgress实体与另一个名为LoanApp的类具有oneToOne关系。 LoanAppMenuProgress表上存在与DB中的LoanApp表关联的外键关联。

我在LoanApp.LoanAppMenuProgress.orm.yml中为我的LoanAppMenuProgress类配置了这个配置:

LoanEv\LoanAppBundle\Entity\LoanApp\LoanAppMenuProgress:
  type:  entity
  repositoryClass: LoanEv\LoanAppBundle\Repository\LoanApp\LoanAppMenuProgress
  table: loan_app_menu_progress
  id:
    id:
      type: integer
      generator: { strategy: auto }

### This is the OWNING side of the relationship
  oneToOne:
    loan_app:
      targetEntity: LoanApp
      inversedBy: loanapp_menu
      joinColumn:
        name: loan_id
        referencedColumnName: id

  fields:
    loan_id:
      type: integer
    menu_id2:
      type: integer
    menu_id3:
      type: integer
    menu_id4:
      type: integer

  lifecycleCallbacks:
    prePersist: [ updateMainMenuStatus ]

这是我的LoanApp.LoanApp.orm.yml文件:

LoanEv\LoanAppBundle\Entity\LoanApp\LoanApp:
  type:  entity
  repositoryClass: LoanEv\LoanAppBundle\Repository\LoanApp\LoanAppRepository
  table: loan_app
  id:
    id:
      type: integer
      generator: { strategy: auto }

## This is the INVERSE side of the relationship.
  oneToOne:
    loanapp_menu:
      targetEntity: LoanAppMenuProgress
      mappedBy: loan_app

  fields:
    bank_id:
      type: integer
  # etc.

在我的LoanAppMenuProgress实体类中,我有以下代码:

namespace LoanEv\LoanAppBundle\Entity\LoanApp;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Util\Debug;

/**
 * LoanEv\LoanAppBundle\Entity\LoanApp\LoanAppMenuProgress
 */
class LoanAppMenuProgress
{
    private $id;

    private $loan_id;

    /**
     * @var LoanEv\LoanAppBundle\Entity\LoanApp\LoanApp
     */
    private $loan_app;

    private $menu_id2 = 0;

    private $menu_id3 = 0;

    private $menu_id4 = 0;

    // ...

    public function updateMainMenuStatus()
    {       
        echo("Inside prePersist's updateMainMenuStatus function. ");
    }
}

从我的LoanAppController类中调用以下代码:

// ...

//Save the menuStatus changes.
echo("About to persist. ");
    $em->persist($menuStatus[0]);
echo("Done persisting.");
    $em->flush();

// ...

当我在LoanAppController中执行代码时,以下内容会写入我的屏幕:

“即将坚持。完成坚持。”

我在输出应该读取的中间缺少那个位:

“即将坚持。内部prePersist的updateMainMenuStatus功能。完成持续。”

更改将被写入数据库,并且除了prePersist()之外,系统的所有功能都按预期工作。我已经在yml设置上挣扎了很长一段时间,所以我最初的假设是我的YAML设置不正确。

文档(据我所知)我提到我应该将lifecycleCallbacks:和prePersist:items添加到yml文件中,然后确保我在持久化实体中有一个公共函数。显然,我错过了一些东西。

有没有人有任何想法?

感谢。

1 个答案:

答案 0 :(得分:5)

只有在执行INSERT类型语句时才会调用prePersist。此事件永远不会触发UPDATE操作。 要在实体进行UPDATEd时执行某些操作,请使用preUpdate。请注意,preUpdate对可以使用相关实体执行的操作有更多限制。

井架