如何在原则2中设置默认值?
当前回答
为@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");
有了这个答案,我鼓励您思考一下,为什么首先需要数据库中的默认值?通常它允许创建非空约束的对象。
其他回答
我使用的解决方法是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');
}
数据库默认值不支持“可移植”。使用数据库默认值的唯一方法是通过columnDefinition映射属性,在该属性中为字段映射到的列指定SQL片段(包括default原因)。
你可以使用:
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
php级别的默认值是首选的,因为这些值在新创建的和持久化的对象上也是正确可用的(在持久化一个新对象后,Doctrine不会返回数据库以获得默认值)。
这些对我都没用。我在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;
这将插入我想要的值。
在实体中设置一个构造函数,并在那里设置默认值。
为@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");
有了这个答案,我鼓励您思考一下,为什么首先需要数据库中的默认值?通常它允许创建非空约束的对象。