我添加了一个自定义类型:
namespace My\SuperBundle\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class Money extends Type
{
const MONEY = 'money';
public function getSqlDeclaration(
array $fieldDeclaration,
AbstractPlatform $platform
) {
return 'DECIMAL(10,2)';
}
public function getName()
{
return self::MONEY;
}
}
在我的应用程序启动:
namespace My\SuperBundle;
use Doctrine\DBAL\Types\Type;
use My\SuperBundle\Types\Money;
class MyBSuperBundle extends Bundle
{
public function boot()
{
//add custom quantity and wight types
$em = $this->container->get('doctrine.orm.entity_manager');
if(!Type::hasType(Money::MONEY)) {
Type::addType(Money::MONEY, 'My\SuperBundle\Types\Money');
}
}
}
然而每次我用以下内容更新数据库:
php app/console doctrine:schema:update --dump-sql
我一直得到以下内容:
ALTER TABLE product_price CHANGE price price DECIMAL(10,2) DEFAULT NULL
除此之外,一切都很好。 DB中的字段是正确的。 是否有理由继续使用相同的数据进行更新?
答案 0 :(得分:9)
您必须覆盖方法requiresSQLCommentHint(AbstractPlatform $platform)
并返回true
。像那样,学说会记住自定义类型。
namespace My\SuperBundle\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class Money extends Type
{
const MONEY = 'money';
public function getSqlDeclaration(
array $fieldDeclaration,
AbstractPlatform $platform
) {
return 'DECIMAL(10,2)';
}
public function getName()
{
return self::MONEY;
}
/**
* @inheritdoc
*/
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}
答案 1 :(得分:4)
使用配置还有另一种方法。
config.yml:
doctrine:
dbal:
types: { money: My\SuperBundle\Types\Money }
connections:
your_connection_name:
mapping_types: { money: money }
来源:
答案 2 :(得分:3)
您没有告诉DBAL平台您的类型,显然,DBAL架构内省实用程序无法识别它。要注册类型,您可以执行以下操作:
use Doctrine\DBAL\Types\Type;
use My\SuperBundle\Types\Money;
class MyBSuperBundle extends Bundle
{
public function boot()
{
/* @var $em \Doctrine\ORM\EntityManager */
$entityManager = $this->container->get('doctrine.orm.entity_manager');
if( ! Type::hasType(Money::MONEY)) {
Type::addType(Money::MONEY, 'My\SuperBundle\Types\Money');
$entityManager
->getConnection()
->getDatabasePlatform()
->registerDoctrineTypeMapping('decimal', Money::MONEY);
}
}
}
这应该可以阻止DBAL抱怨架构差异。
答案 3 :(得分:1)
我遇到了与ZF2相同的问题。
我在自定义类型名称中解析了删除连字符。
错:
'doctrine_type_mappings' => [
'custom-type' => 'custom-type'
],
好:
'doctrine_type_mappings' => [
'customtype' => 'customtype'
],
有关Zend Framework 2中实现的更多详细信息:https://github.com/doctrine/DoctrineORMModule/blob/master/docs/EXTRAS_ORM.md
我希望这可以帮助别人。