在新实体上触发自动生成字段(Symfony 中的 Doctrine)/避免违反完整性约束字段不能为空

Trigger auto generation of field on new Entity (Doctrine in Symfony) / avoid Integrity constraint violation field cannot be null

使用 Symfony 3.x 和 Doctrine 我遇到了这个问题: 实体"Foo"定义如下:

/**
 * @ORM\Entity
 * @ORM\Table(name="foo")
 */
class Foo
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $incr_int;

    ...
}

撇开 $id 和 $incr_int 将(总是?)是相同的值我在创建 Foo 类型的新实体时收到以下错误:

An exception occurred while executing 'INSERT INTO foo (incr_int) VALUES (?)' with params [null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'incr_int' cannot be null

虽然从错误本身来看这似乎是有道理的,但我不知道如何在像这样创建 Foo 时修复它(我认为这是 Symfony 中的标准方法?):

$foo = new Foo();
$em->persist($foo);     // $em is the entity manager
$em->flush();

就像我期望的那样,如果我从 Foo 中删除 $incr_int 字段,它会起作用,因为唯一剩余的字段 $id 是通过将最后插入的 id 值增加 1 自动生成的。我假设这种行为$incr_int 字段应该相同。好吧......显然不是,我不明白为什么。非常感谢任何帮助。

我的代码中有 2 个问题(感谢@nospor)。

  1. A table 只能有一个自动递增字段(第二个也没什么意义)。
  2. 创建新实体时,在真正更新数据库(刷新实体管理器)时生成 id。

我可以通过删除第二个自动递增条件并创建具有必填字段(此处仅自动生成的 id 字段)的实体然后刷新它来解决此问题。刷新后,我能够检索 id 并生成第二个字段的值,其中包含一个计算值,该值也取决于 id 值。