如何使用Symfony 2在Doctrine 2中添加BLOB类型

时间:2011-10-12 10:38:34

标签: doctrine-orm blob symfony

在Symfony 2中,我生成了一个Bundle,用于将任何类型的文档存储到数据库中,但我需要BLOB列类型。

Tnx到this question我将类BlobType添加到Doctrine DBAL中,但是要使用新列类型我必须更改

学说\ DBAL \类型\类型

[...]

const BLOB = 'blob';

[...]

private static $_typesMap = array(
    [...],
    self::BLOB => 'Doctrine\DBAL\Types\BlobType',
);

Doctrine \ DBAL \ Platforms \ MySqlPlatform (如果我更改了Doctrine \ DBAL \ Platforms \ AbstractPlatform,可能会更好)

[...]
protected function initializeDoctrineTypeMappings()
{
    $this->doctrineTypeMapping = array(
        [...],
        'blob'          => 'blob',
    );
}

[...]

/**
 * Obtain DBMS specific SQL to be used to create time fields in statements
 * like CREATE TABLE.
 *
 * @param array $fieldDeclaration
 * @return string
 */
public function getBlobTypeDeclarationSQL(array $fieldDeclaration) 
{
    return 'BLOB';
}   

现在我没有'漂亮解决方案'的mouch时间,但是将来我想恢复Doctrine类并能够将新列类型分配到Symfony 2 bootstrap中。 我想我应该编辑我的app / bootstrap.php.cache,但我不知道如何干预。

3 个答案:

答案 0 :(得分:3)

这对我有用:

  1. 创建您的blobtype(请参阅https://gist.github.com/525030/38a0dd6a70e58f39e964ec53c746457dd37a5f58

  2. 将此添加到您的Bundle初始化(/src/YOURDOMAIN/YOURBUNDLE/YOURDOMAINYOUBUNDLE.php)

    class YourBundle extends Bundle
    {
        public function boot()
        {
            $em = $this->container->get('doctrine.orm.entity_manager');
            Type::addType('blob', 'YOURDOMAIN\YOURBUNDLE\YOURTYPEDIRECTORY\BlobType');
            $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('blob','blob');        
        }
    }
    

答案 1 :(得分:2)

XXXBundle :: boot()中的注册 blob 的小改进,但在单元测试期间可能是必要的。

class XXXBundle extends Bundle
{
   public function boot()
   {
      // Add blob type
      if(!Type::hasType('blob')) {
         Type::addType('blob', '{CLASS_PATH}\\Blob');
      }

      // Add blob type to current connection.
      // Notice: during tests there can be multiple connections to db so 
      // it will be needed to add 'blob' to all new connections if not defined. 
      $em = $this->container->get('doctrine.orm.entity_manager');
      if (!$em->getConnection()->getDatabasePlatform()->hasDoctrineTypeMappingFor('blob')) {
           $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('blob','blob');
      }
}

答案 2 :(得分:1)

我刚刚发现了这个要点: https://gist.github.com/525030/38a0dd6a70e58f39e964ec53c746457dd37a5f58

应用程序/ bootstrap.php中:

<?php

// ...
$em = Doctrine\ORM\EntityManager::create($conn, $config, $evm);

// types registration
Doctrine\DBAL\Types\Type::addType('blob', 'Doctrine\DBAL\Types\Blob');
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('BLOB', 'blob');

BTW bootstrap.cache.php是自动生成的AFAIK ..所以那里的更改会被覆盖。