如何在原则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");
有了这个答案,我鼓励您思考一下,为什么首先需要数据库中的默认值?通常它允许创建非空约束的对象。
其他回答
这些对我都没用。我在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>
数据库默认值不支持“可移植”。使用数据库默认值的唯一方法是通过columnDefinition映射属性,在该属性中为字段映射到的列指定SQL片段(包括default原因)。
你可以使用:
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
php级别的默认值是首选的,因为这些值在新创建的和持久化的对象上也是正确可用的(在持久化一个新对象后,Doctrine不会返回数据库以获得默认值)。
我使用的解决方法是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');
}
下面是如何在PHP 8中使用属性来做到这一点。
#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => 0])]
#[Assert\NotNull()]
private bool $isFavorite = false;
推荐文章
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在php中创建可选参数?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 如何从一个查询插入多行使用雄辩/流利
- 在PHP单元测试执行期间,如何在CLI中输出?