Symfony2/Doctrine2 如何自动生成主键?
我已经创建了所有实体和数据库。
在我的 Symfony2 Controller 中,我这样做:
<?php
/**
* @Route("/myroute", name="myroute")
* @Template()
*/
public function myrouteAction()
{
/* Page de Création d'un retrait ou d'une réexpédition. */
$obj = new Utilisateur();
$obj->setUsermail('contact@mydomain.com');
$obj->setUserpass('coucou');
$obj->setUservalide('1');
$em = $this->getDoctrine()->getEntityManager();
$em->persist($obj);
$em->flush();
// [...]
}
用于测试。 第一次一切顺利(Utilisateur 表是空的)。现在,当我再次调用这个函数时,我得到:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' 500 Internal Server Error - PDOException
我只是想让 Symfony-Doctrine-Mysql 自动增加标识符。
最佳答案
希望这会有所帮助:假设您正在使用注释和 Doctrine ORM,您需要将策略设置为在您的对象上自动 - 来自文档 (http://symfony.com/doc/current/book/doctrine.html)
/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
--> * @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
记得在修改对象后更新数据库模式。
关于mysql - 在 symfony2 和 mysql 中生成主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804052/