2013-05-29 33 views
2

我想根據UUID和二進制(16)中的存儲製作主鍵。Doctrine2定製類型不能像主鍵一樣工作Symfony2

爲此我創建主義新類型 - 「二進制」

class BinaryType extends Type 
{ 
const BINARY = 'binary'; 

public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform) 
{ 
    return sprintf('BINARY(%d)', $fieldDeclaration['length']); 
} 

public function getName() 
{ 
    return self::BINARY; 
} 

public function convertToPhpValue($value, AbstractPlatform $platform) 
{ 

    if ($value !== null) { 
     $value= unpack('H*', $value); 
     return array_shift($value); 
    } 
} 

public function convertToDatabaseValue($value, AbstractPlatform $platform) 
{ 
    if ($value !== null) { 
     return pack('H*', $value); 
    } 
} 

} 

而且註冊此類型:

class MyBundle extends Bundle 
{ 
    public function boot() 
    { 
    Type::addType('binary', '...\Doctrine2\BinaryType'); 
    } 
} 

問:爲什麼這種類型的工作在一個簡單的領域不錯,但沒有使用主鍵(註解@ORM \ Id的字段),字段沒有出現。

示例不工作註釋。在這種情況下,不會出現db中的任何一行:

/** 
* @ORM\Id 
* @ORM\Column(type="binary", length=16, name="id", nullable=false) 
* 
* @ORM\GeneratedValue(strategy="NONE") 
*/ 
private $id; 

/** 
* 
* @ORM\Column(name="second_id", type="integer", nullable=false) 
*/ 
private $secondId; 

工作註釋示例。我們看到從數據庫和id行的二進制類型:

/** 
* 
* @ORM\Column(type="binary", length=16, name="id", nullable=false) 
* @ORM\GeneratedValue(strategy="NONE") 
*/ 
private $id; 

/** 
* @ORM\Id 
* @ORM\Column(name="second_id", type="integer", nullable=false) 
*/ 
private $secondId; 

回答

1

我花了好幾個小時,在這個確切的問題,因爲我需要做的一樣好。我最終得到了確切的代碼來處理一個細微的變化:省略@ ORM/GeneratedValue(strategy =「NONE」)。

換句話說,如果你改變了這個

/** 
* @ORM\Id 
* @ORM\Column(type="binary", length=16, name="id", nullable=false) 
* 
* @ORM\GeneratedValue(strategy="NONE") 
*/ 
private $id; 

對此

/** 
* @ORM\Id 
* @ORM\Column(type="binary", length=16, name="id", nullable=false) 
*/ 
private $id; 

它爲我工作。

還有一件事,如果你想擁有ID生成,你必須實現自己的發電機 像:

use Doctrine\ORM\EntityManager; 
use Doctrine\ORM\Id\AbstractIdGenerator; 

class GuidGenerator extends AbstractIdGenerator 
{ 
    public function generate(EntityManager $em, $entity) 
    { 
     //return generated id 
    } 
} 

,改變你的註釋

/** 
* @ORM\Id 
* @ORM\Column(type="binary", length=16, name="id", nullable=false) 
* @ORM\GeneratedValue(strategy="CUSTOM") 
* @ORM\CustomIdGenerator(class="path\to\IDGenerators\GuidGenerator") 
*/ 
private $id; 

我知道你大概移動了,但只是發佈給下一個人。

相關問題