2012-02-25 37 views
2

我正在使用symfony2,我有一个表,我想手动分配ID。Symfony2,手动分配表ID值

在学说的文件,我发现这一点:

标识符生成策略

"NONE: Tells Doctrine that the identifiers are assigned (and thus generated) 
by your code. The assignment must take place before a new entity is passed to 
EntityManager#persist. 
NONE is the same as leaving off the @GeneratedValue entirely." 

注重这一点:“一个新的实体传递给恩之前转让必须发生.. “

我该如何做到这一点?

我这样做:

$empleado->setId("989865446"); 

但它说:

Entity of type Entity\Empleado is missing an assigned ID. The identifier 
generation strategy for this entity requires the ID field to be populated before 
EntityManager#persist() is called. If you want automatically generated 
identifiers instead you need to adjust the metadata mapping accordingly. 

编辑:

/** 
* @var integer $id 
* @ORM\Column(name="id", type="integer", nullable=false) 
* @ORM\Id 
*/ 
private $id; 

public function setId($id) 
{ 
    $this->id = $id; 
} 
+1

,你能否告诉我们有关的代码围绕'$ empleado-> setId()'? – Problematic 2012-02-25 16:36:26

+0

你是如何实现'setId()'的? – greg0ire 2012-02-25 17:00:26

+0

不用说(但我会说)无论如何,确保你的id属性被称为id。 – Cerad 2012-02-25 21:11:32

回答

2

您发布的代码是正确的,所以错误必须与您构建对象的方式以及何时调用persist()有关。

有一个类似的问题在这里: Set value for the primay key with strategy set to NONE

你运行的Symfony 2/2学说的最新版本?

请尝试使其成为上述答案中建议的必需构造函数参数 - 这应该使设置ID之前无法调用persist()。错误消息意味着它说的 - 你必须先分配ID,只有呼叫持续。

您正在创建对象,正确吗?您的代码应该是这样的(在这里我展示它是如何通过构造所需的ID工作,但它应该与SETID(工作)的做法太):

$empleado = new Entity\Empleado("989865446"); 
//set other properties 
$em->persist($empleado); 
+0

谢谢马特。 :) – 2012-03-11 08:05:00

+0

我尝试了两种方法,用setId和构造函数。该ID设置正确,但随后保持下一个自动增量。 – afilina 2013-10-07 20:43:16

+0

@afilina你确定你的ID属性没有'@ GeneratedValue'注解吗? – 2013-10-11 20:01:01