php Doctrine 中的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3376881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default value in Doctrine
提问by Jiew Meng
How do I set a default value in Doctrine 2?
如何在 Doctrine 2 中设置默认值?
回答by iv3ndy
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @ORM\Column(name="myColumn", type="integer", options={"default" : 0})
*/
private $myColumn;
...
}
Note that this uses SQL DEFAULT, which is not supported for some fields like BLOBand TEXT.
请注意,这使用了 SQL DEFAULT,而某些字段(例如BLOB和)不支持该 SQL TEXT。
回答by romanb
Database default values are not "portably" supported. The only way to use database default values is through the columnDefinitionmapping attribute where you specify the SQLsnippet (DEFAULTcause inclusive) for the column the field is mapped to.
不“可移植”支持数据库默认值。使用数据库默认值的唯一方法是通过columnDefinitionmapping 属性,您可以在其中指定字段映射到的列的SQL片段(DEFAULT包含原因)。
You can use:
您可以使用:
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
PHP-level default values are preferred as these are also properly available on newly created and persisted objects (Doctrine will not go back to the database after persisting a new object to get the default values).
PHP 级别的默认值是首选,因为它们也可以在新创建和持久化的对象上正确可用(在持久化新对象以获取默认值后,Doctrine 不会返回到数据库)。
回答by Jeremy Hicks
Set up a constructor in your entity and set the default value there.
在您的实体中设置一个构造函数并在那里设置默认值。
回答by Stanislav Terletskyi
Use:
用:
options={"default":"foo bar"}
and not:
并不是:
options={"default"="foo bar"}
For instance:
例如:
/**
* @ORM\Column(name="foo", type="smallint", options={"default":0})
*/
private $foo
回答by Callistino
Update
更新
One more reason why read the documentationfor Symfony will never go out of trend. There is a simple solution for my specific case and is to set the field typeoption empty_datato a default value.
阅读Symfony文档的另一个原因永远不会过时。对于我的具体情况,有一个简单的解决方案,就是将field type选项empty_data设置为默认值。
Again, this solution is only for the scenario where an empty input in a form sets the DB field to null.
同样,此解决方案仅适用于表单中的空输入将 DB 字段设置为空的情况。
Background
背景
None of the previous answers helped me with my specific scenario but I found a solution.
以前的答案都没有帮助我解决我的具体情况,但我找到了解决方案。
I had a form field that needed to behave as follow:
我有一个表单字段,需要按如下方式运行:
- Not required, could be left blank. (Used 'required' => false)
- If left blank, it should default to a given value. For better user experience, I did not set the default value on the input field but rather used the html attribute 'placeholder' since it is less obtrusive.
- 不需要,可以留空。(使用“必需”=> 假)
- 如果留空,则应默认为给定值。为了更好的用户体验,我没有在输入字段上设置默认值,而是使用了 html 属性“占位符”,因为它不那么突兀。
I then tried all the recommendations given in here. Let me list them:
然后我尝试了这里给出的所有建议。让我列出它们:
- Set a default value when for the entity property:
- 为实体属性设置默认值:
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
- Use the options annotation:
- 使用选项注释:
@ORM\Column(name="foo", options={"default":"foo bar"})
- Set the default value on the constructor:
- 在构造函数上设置默认值:
/**
* @Entity
*/
class myEntity {
...
public function __construct()
{
$this->myColumn = 'myDefaultValue';
}
...
}
这一切都没有奏效,这完全是因为 Symfony 如何使用您的 Entity 类。
IMPORTANT
重要的
Symfony form fields override default values set on the Entity class.Meaning, your schema for your DB can have a default value defined but if you leave a non-required field empty when submitting your form, the form->handleRequest()inside your form->isValid()method will override those default values on your Entityclass and set them to the input field values. If the input field values are blank, then it will set the Entityproperty to null.
Symfony 表单域会覆盖 Entity 类上设置的默认值。这意味着,您的数据库架构可以定义默认值,但如果您在提交表单时将非必填字段留空,则form->handleRequest()内部form->isValid()方法将覆盖您的Entity类中的这些默认值并将它们设置为输入字段值。如果输入字段值为空,则会将该Entity属性设置为null。
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
My Workaround
我的解决方法
Set the default value on your controller after form->handleRequest()inside your form->isValid()method:
form->handleRequest()在form->isValid()方法内部之后在控制器上设置默认值:
...
if ($myEntity->getMyColumn() === null) {
$myEntity->setMyColumn('myDefaultValue');
}
...
Not a beautiful solution but it works. I could probably make a validation groupbut there may be people that see this issue as a data transformationrather than data validation, I leave it to you to decide.
不是一个漂亮的解决方案,但它有效。我可能会做一个,validation group但可能有人认为这个问题是数据转换而不是数据验证,我把它留给你来决定。
Override Setter (Does Not Work)
覆盖设置器(不起作用)
I also tried to override the Entitysetter this way:
我还尝试以Entity这种方式覆盖setter:
...
/**
* Set myColumn
*
* @param string $myColumn
*
* @return myEntity
*/
public function setMyColumn($myColumn)
{
$this->myColumn = ($myColumn === null || $myColumn === '') ? 'myDefaultValue' : $myColumn;
return $this;
}
...
This, even though it looks cleaner, it doesn't work. The reason being that the evil form->handleRequest()method does not use the Model's setter methods to update the data (dig into form->setData()for more details).
这样,即使看起来更干净,也行不通。原因是邪恶的form->handleRequest()方法不使用模型的 setter 方法来更新数据(深入form->setData()了解更多细节)。
回答by Jiew Meng
The workaround I used was a LifeCycleCallback. Still waiting to see if there is any more "native" method, for instance @Column(type="string", default="hello default value").
我使用的解决方法是一个LifeCycleCallback. 仍在等待查看是否有更多“本机”方法,例如@Column(type="string", default="hello default value")。
/**
* @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');
}
回答by Andrew Zhilin
You can do it using xml as well:
您也可以使用 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>
回答by Putna
Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.
这是我为自己解决的方法。下面是一个具有 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'
回答by metric152
None of this worked for me. I found some documentation on doctrine's site that says to set the value directly to set a default value.
这些都不适合我。我在学说网站上找到了一些文档,上面写着要直接设置值以设置默认值。
private $default = 0;
This inserted the value I wanted.
这插入了我想要的值。
回答by Alex Hoang
Works for me on a mysql database also:
在 mysql 数据库上也适用于我:
Entity\Entity_name:
type: entity
table: table_name
fields:
field_name:
type: integer
nullable: true
options:
default: 1

