Symfony Doctrine2:跳过未设置的列

Symfony Doctrine2:跳过未设置的列,symfony,doctrine-orm,Symfony,Doctrine Orm,我有以下实体: class Employee { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $employeeId; /** * @ORM\Column(type="string", length=45, unique=true) */ protected $username; /** * @ORM\Column(type="s

我有以下实体:

class Employee {

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

/**
 * @ORM\Column(type="string", length=45, unique=true)
 */
protected $username;

/**
 * @ORM\Column(type="string", length=255, nullable=false)
 */
protected $email;
我正在运行以下代码:

$employee = new Employee();
$employee->setUsername('test');

$em = $this->getDoctrine()->getManager();
$em->persist($employee);
$em->flush();
正如你们所看到的,我并没有为email列设置值

但在我看来:

SQLSTATE[23000]:完整性约束冲突:1048列“电子邮件”不能为空

因为条令将所有实体列添加到INSERT查询,并为电子邮件列设置空值


有没有办法跳过插入时未设置的列?或者要将“”插入(空字符串)作为非空字符串列的默认值?

我似乎只需要使用实体构造来设置默认值:

__construct() {
    $this->email = '';
}

这是数据模型的问题,而不是条令的问题。您明确声明每个记录在电子邮件列中都应该有一些值。所以,要么从实体中删除NOTNULL约束,要么在电子邮件列上设置一些值。在这种情况下,条令只是做你告诉它做的事

您可以允许列为
null
,设置
null=true

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
protected $email;
这不会引发SQL错误。但如果要保持一致,请使用,以便在持久化之前处理空字段:

use Symfony\Component\Validator\Constraints as Assert;

...

/**
 * @Assert\NotBlank()
 * @ORM\Column(type="string", length=255)
 */
protected $email;
通过这种方式,您可以以更具体的方式处理验证错误,如文档中所述,例如:

$author = new Author();
// ... do something to the $author object

$validator = $this->get('validator');
$errors = $validator->validate($author);

if (count($errors) > 0) {
    return new Response(print_r($errors, true));
} else {
    return new Response('The author is valid! Yes!');
}

如果您只需要列的纯默认值,.

那么如果我们必须存储空值本身呢?