如何在Doctrine 2中设置默认值? php
<?php /** * @Entity */ class myEntity { /** * @var string * * @ORM\Column(name="myColumn", type="integer", options={"default" : 0}) */ private $myColumn; ... }
请注意,这使用SQL DEFAULT
,某些字段(例如BLOB
和TEXT
)不支持SQL DEFAULT
。 sql
添加到@romanb辉煌的答案。 数据库
这会增长迁移的开销,由于您显然没法建立具备非null约束且没有默认值的字段。 bootstrap
// 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");
有了这个答案,我建议您考虑一下为何首先须要数据库中的默认值? 一般,它容许建立具备非null约束的对象。 app
使用: ide
options={"default":"foo bar"}
并非: post
options={"default"="foo bar"}
例如: ui
/** * @ORM\Column(name="foo", type="smallint", options={"default":0}) */ private $foo
我也遇到一样的问题。 我想将数据库的默认值(自动)添加到实体中。 猜猜是什么,我作到了:) this
<?php /** * Created by JetBrains PhpStorm. * User: Steffen * Date: 27-6-13 * Time: 15:36 * To change this template use File | Settings | File Templates. */ require_once 'bootstrap.php'; $em->getConfiguration()->setMetadataDriverImpl( new \Doctrine\ORM\Mapping\Driver\DatabaseDriver( $em->getConnection()->getSchemaManager() ) ); $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager()); $driver->setNamespace('Models\\'); $em->getConfiguration()->setMetadataDriverImpl($driver); $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); $metadata = $cmf->getAllMetadata(); // Little hack to have default values for your entities... foreach ($metadata as $k => $t) { foreach ($t->getFieldNames() as $fieldName) { $correctFieldName = \Doctrine\Common\Util\Inflector::tableize($fieldName); $columns = $tan = $em->getConnection()->getSchemaManager()->listTableColumns($t->getTableName()); foreach ($columns as $column) { if ($column->getName() == $correctFieldName) { // We skip DateTime, because this needs to be a DateTime object. if ($column->getType() != 'DateTime') { $metadata[$k]->fieldMappings[$fieldName]['default'] = $column->getDefault(); } break; } } } } // GENERATE PHP ENTITIES! $entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator(); $entityGenerator->setGenerateAnnotations(true); $entityGenerator->setGenerateStubMethods(true); $entityGenerator->setRegenerateEntityIfExists(true); $entityGenerator->setUpdateEntityIfExists(false); $entityGenerator->generate($metadata, __DIR__); echo "Entities created";
若是您为实体使用yaml定义,那么如下内容对我在postgresql数据库中有效: spa
Entity\Entity_name: type: entity table: table_name fields: field_name: type: boolean nullable: false options: default: false