在不刷新或 setId() 的情况下测试时在 Doctrine2-Entity 中设置显式 Id
Set explicit Id in Doctrine2-Entity while testing without flushing or setId()
我使用实体
id:
id:
type: string
length: 36
id: true
generator:
strategy: UUID
所以我没有setId()-方法。测试时,这是我创建实体的方式:
$person = new Person();
$person->setFirsname('Foo');
...
$manager->persit($person);
// no flush
我试过了
$metadata = $manager->getClassMetaData('Acme\Entities\Person');
$metadata->setIdGenerator(new AssignedGenerator());
$person = new Person();
....
但它说它缺少分配的 ID,但我不能在没有 setId() 的情况下设置它(而且我不想要 setId() 在我的实体中)。
我对生成器进行了一些实验,并尝试了这个:
...
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
class AutoIncGenerator extends AbstractIdGenerator
{
public $count = 0;
public function generate(EntityManager $em, $entity)
{
$this->count++;
return $this->count;
}
}
它完全符合我的需要。每个对象都有一个唯一编号范围的 id (auto inc)。
不需要 flush() 或 setId()。
我使用实体
id:
id:
type: string
length: 36
id: true
generator:
strategy: UUID
所以我没有setId()-方法。测试时,这是我创建实体的方式:
$person = new Person();
$person->setFirsname('Foo');
...
$manager->persit($person);
// no flush
我试过了
$metadata = $manager->getClassMetaData('Acme\Entities\Person');
$metadata->setIdGenerator(new AssignedGenerator());
$person = new Person();
....
但它说它缺少分配的 ID,但我不能在没有 setId() 的情况下设置它(而且我不想要 setId() 在我的实体中)。
我对生成器进行了一些实验,并尝试了这个:
...
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
class AutoIncGenerator extends AbstractIdGenerator
{
public $count = 0;
public function generate(EntityManager $em, $entity)
{
$this->count++;
return $this->count;
}
}
它完全符合我的需要。每个对象都有一个唯一编号范围的 id (auto inc)。
不需要 flush() 或 setId()。