use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document()
*/
class My_Doctrine_Model
{
/** @ODM\id */
protected $id;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
return $this;
}
}
代码
$myModel = new My_Doctrine_Model();
$myModel->setId(new MongoId());
// Id is my set id
$dm->persist($myModel);
// Id is my set id
$dm->flush();
// Id is overwritten and the object is inserted with an other one
为什么Doctrine会覆盖我的设置ID?有没有办法阻止这种情况?
当检查是否设置了ID时,新{1}设置为PersistenceBuilder::prepareInsertData
。我不知道为什么id字段被排除在更改集之外。
我阅读了更多代码,发现原因是if
中的最后一个UnitOfWork::getDocumentActualData
。
else if ( ! $class->isIdentifier($name) || $class->isIdGeneratorNone()) {
$actualData[$name] = $value;
}
没有else
因此没有为id设置值。
这是开发人员慎重的设计选择吗?
这是在最近的一次提交中更新的,我还没有更新到。我不完全确定这是有意的。
https://github.com/doctrine/mongodb-odm/commit/fb2447c01cb8968255383ac5700f95b4327468a3#L2L503
答案 0 :(得分:2)
您可以使用Doctrine ODM的注释来使用自定义ID策略,例如 -
/** Document */
class MyPersistentClass
{
/** @Id(strategy="NONE") */
private $id;
public function setId($id)
{
$this->id = $id;
}
//...
}
有关Doctrine ODM可用的不同自定义ID策略的更多信息,请访问此处 - http://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/basic-mapping.html#basic-mapping-identifiers