我正在使用 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."
注意这一点:“分配必须在新实体传递给 En.. 之前进行。”
我如何实现这一目标?
我正在这样做:
$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;
}
最佳答案
您发布的代码是正确的,因此错误一定与您构造对象的方式以及调用 persist() 的时间有关。
这里有一个类似的问题: Set value for the primay key with strategy set to NONE
您正在运行最新版本的 Symfony 2/Doctrine 2 吗?
尝试按照上面答案中的建议将其设置为必需的构造函数参数 - 这应该使得在设置 ID 之前不可能调用 persist() 。错误消息的含义正如其所言 - 您必须先分配 ID,然后调用 persist。
您正在正常创建对象,对吗?您的代码应该如下所示(这里我展示了它如何使用构造函数所需的 ID,但它也应该使用 setId() 方法):
$empleado = new Entity\Empleado("989865446");
//set other properties
$em->persist($empleado);
关于Symfony2,手动分配表id值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9445776/