我正在使用带有symfony2和sqlite数据库的doctrine,我在插入值时遇到问题,因为id不再增加。我刚刚更改了一个字段注释,我删除了数据库并再次创建它:
php app/console doctrine:database:create --env=dev
php app/console doctrine:schema:update --force
响应:
Database schema updated successfully! "4" queries were executed
我第二次完成了更新,而且
Database schema updated successfully! "14" queries were executed
我有一个班级“帖子”:
namespace Llafon\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="post")
* @ORM\Entity
*/
class Post {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY") //I also tried "AUTO"
*/
protected $id;
/**
* @ORM\Column(type="string", length=100, nullable=false)
*/
protected $title;
/**
* @ORM\Column(type="text", nullable=false)
*/
protected $content;
/**
* @ORM\Column(type="datetime", nullable=false)
*/
protected $date;
/**
* @ORM\ManyToOne(targetEntity="User") //This variable was an integer before
* @ORM\JoinColumn(name="id", referencedColumnName="id")
*/
protected $author;
/**
* @ORM\Column(type="string", nullable=false)
*/
protected $image_name;
public function __construct() {
$this->date = new \DateTime();
}
现在我已经这样插入:
public function addAction(Request $request) {
$post = new Post();
$user = $this->container->get('security.context')->getToken()->getUser();
$post->setAuthor($user); //$user is not null
$post->setContent("zz");
$post->setImageName("aaa");
$post->setTitle("fff");
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();die();
}
第二次执行此函数时出现此错误:
An exception occurred while executing 'INSERT INTO post (title, content, date, image_name, id) VALUES (?, ?, ?, ?, ?)' with params ["fff", "zz", "2015-10-25 21:45:37", "aaa", 1]:
SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: post.id
所以我们在这里可以看到自动增量不起作用(id应为'2')。
我也清除了symfony缓存,但它没有改变任何东西。
但是,如果我将$ author类型更改为整数(而不是join),则自动增量会起作用。
提前感谢您的帮助。
答案 0 :(得分:0)
感谢Artamiel,问题在于列名。 “既然你没有为$ id设置一个名称,Doctrine会自动将属性的名称转换为列名。然后当我们查看你的$ author属性时,我们清楚地看到 - JoinColumn(name =”id“)导致例如,将名称更改为author_id,您将很高兴“