2017-02-20 43 views
0

我有一個Question實體,其名稱爲code。我想在默認的Doctrine註釋中設置code的值等於idSymfony + Doctrine - 設置屬性默認值等於ID

這是我試過,但我得到了一個錯誤:

/** 
* @ORM\Column(type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

/** 
* @ORM\Column(type="integer") 
*/ 
private $code = $id; 

或者:

/** 
* @ORM\Column(type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

/** 
* @ORM\Column(type="integer", options = {"default": $id}) 
*/ 
private $code; 

感謝。

+0

複製id的目的是什麼? – OlivierC

回答

2

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html

我不知道你有什麼需要,但也許postPersist事件是你想要什麼:

postPersist - The postPersist event occurs for an entity after the entity has been made persistent. It will be invoked after the database insert operations. Generated primary key values are available in the postPersist event.

然後在您的實體:

/** 
* @ORM\Column(type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

/** 
* @ORM\Column(type="integer") 
*/ 
private $code; 

/** @PostPersist */ 
public function doStuffOnPostPersist() 
{ 
    $this->code = $this->id; 
} 

這是很重要理解你的學說實體只有在被保留後纔會有ID,因此在後續保留事件之後。