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


当前回答

下面是如何在PHP 8中使用属性来做到这一点。

#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => 0])]
#[Assert\NotNull()]
private bool $isFavorite = false;

其他回答

这些对我都没用。我在doctrine的网站上找到了一些文档,上面说直接设置值来设置默认值。

https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/faq.html#how-can-i-add-default-values-to-a-column

private $default = 0;

这将插入我想要的值。

你也可以使用xml:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

下面是我自己解决问题的方法。下面是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'

如果对实体使用yaml定义, 以下工作为我在postgresql数据库:

Entity\Entity_name:
    type: entity
    table: table_name
    fields: 
        field_name:
            type: boolean
            nullable: false
            options:
                default: false

我使用的解决方法是LifeCycleCallback。仍然在等待是否有更多的“原生”方法,例如@Column(type="string", default="hello默认值")。

/**
 * @Entity @Table(name="posts") @HasLifeCycleCallbacks
 */
class Post implements Node, \Zend_Acl_Resource_Interface {

...

/**
 * @PrePersist
 */
function onPrePersist() {
    // set default date
    $this->dtPosted = date('Y-m-d H:m:s');
}