如何在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