Symfony2,手动分配表id值

标签 symfony

我正在使用 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/

相关文章:

symfony - 开源 Symfony2 项目

php - Symfony2 和 Doctrine2 : No identifier/primary key specified for Entity "X". 每个实体必须有一个标识符/主键

composer-php - Composer 无法执行应用程序/控制台缓存 :clear on symfony 3

symfony - 什么是 symfony 桥接、捆绑和供应商?

Symfony2 phpunit 给出 503 错误

symfony - Sonata Admin Bundle 向自定义管理员角色授予权限

mysql - Symfony2 应用程序如何使用 MySQL 内存存储引擎?

php - Symfony2 - 如何在提交表单后从唯一约束错误中恢复?

php - 我该如何解决 "Type error: Argument 2 passed to ... must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile"?

Symfony2,如何访问表单内的实体值?