如何在原则2中设置默认值?


当前回答

虽然在构造函数中设置值可以工作,但使用Doctrine Lifecycle事件可能是更好的解决方案。

通过利用prePersist生命周期事件,您可以仅在初始持久化时为您的实体设置默认值。

其他回答

在实体中设置一个构造函数,并在那里设置默认值。

<?php
/**
 * @Entity
 */
class myEntity {
    /**
     * @var string
     *
     * @ORM\Column(name="myColumn", type="integer", options={"default" : 0})
     */
    private $myColumn;
    ...
}

注意,这里使用的是SQL DEFAULT,而某些字段(如BLOB和TEXT)不支持SQL DEFAULT。

下面是我自己解决问题的方法。下面是MySQL默认值的实体示例。但是,这也需要在您的实体中设置一个构造函数,并在那里设置默认值。

Entity\Example:
  type: entity
  table: example
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    label:
      type: string
      columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'

为@romanb的精彩回答锦上添花。

这在迁移中增加了一点开销,因为您显然不能创建一个非空约束且没有默认值的字段。

// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

//lets add property without not null contraint        
$this->addSql("ALTER TABLE tablename ADD property BOOLEAN");

//get the default value for property       
$object = new Object();
$defaultValue = $menuItem->getProperty() ? "true":"false";

$this->addSql("UPDATE tablename SET property = {$defaultValue}");

//not you can add constraint
$this->addSql("ALTER TABLE tablename ALTER property SET NOT NULL");

有了这个答案,我鼓励您思考一下,为什么首先需要数据库中的默认值?通常它允许创建非空约束的对象。

工作对我的mysql数据库也:

Entity\Entity_name:
    type: entity
    table: table_name
    fields: 
        field_name:
            type: integer
            nullable: true
            options:
                default: 1