3

当我发送带有空白字段的表单时,我收到错误消息SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null。我发现修复它的唯一方法是在实体文件中设置一个默认值:

 * @ORM\Column(type="string", length=100)
 */
protected $image="";

并像这样更改设置器:

public function setImage($image){
 if(!isset($image)) {
//its really empty but it works only in this way     
}
     else {
    $this->image = $image;
    }  

我认为这非常严重......对此有什么解释吗?还有另一种方法吗?}

4

2 回答 2

7

如果该字段image不是必需的,您可以将其设置为,nullable这样 Doctrine 将知道这一点并将该列设置为可为空。

这样,不会违反约束,因为该字段可以为空。要使用 Doctrine 注释使字段可以为空,只需添加nullable = true如下ORM\Column定义:

@ORM\Column(type="string", length=100, nullable=true)

默认情况下,所有列都是nullable=false这样,当尝试在其中保留空值时,它们将抛出一个约束验证异常。

问候,
马特

于 2012-04-23T20:29:34.770 回答
2

为什么在这里部分回答:

Symfony2 表单将空白字符串解释为空值

这段代码绕过了它,因为当 Symfony 设置$image为 null 并调用$entity->setImage(null)时,这段代码不会改变$image成员。

public function setImage($image){
    if(!isset($image)) {
        // $image is null, symfony was trying to set $this->image to null, prevent it
    } else {
        $this->image = $image;
    }
}

这更明确(而且谁想要那个奇怪的空语句?)。它表达了您的意图,$this->image不能为空(如果您不使其可为空,则与数据库定义匹配)

public function setImage($image){
    if(isset($image)) {
        // $image not null, go ahead and use it
        $this->image = $image;
    }
}

无论哪种方式,您都需要初始化,$this->image否则它将默认为null.

于 2013-10-01T06:22:47.030 回答