在使用Doctrine MongoDB ODM时如何存储ObjectId?

Day*_*son 4 php doctrine mongodb doctrine-orm

我想手动存储引用,而不是让ODM使用DBRef类型.

我可以选择存储我想引用的_id作为@String(例如 - "4e18e625c2749a260e000024"),但是如何ObjectId在这个字段中存储一个实例呢?

new \MongoId("4e18e625c2749a260e000024") <-- what's the annotation for this type?
Run Code Online (Sandbox Code Playgroud)

使用MongoId对象而不是字符串保存它将为我节省一半的空间.它与@Id注释使用的数据类型相同,但@Id只能在Document中使用一次.

什么是正确的注释来实现这一目标?

Day*_*son 9

更新:现在有这种类型的官方支持.使用@ObjectId@Field(type="object_id")在注释中使用ObjectId/MongoId类型.没有必要使用下面的解决方案.

另外,请使用github.com/doctrine/mongodb-odm中的最新主代码,并避免在网站上使用该版本(它已过时).


解决方案(已弃用)

看起来还没有支持.我在IRC频道上讨论了这个问题并在此打开了一张票:https://github.com/doctrine/mongodb-odm/issues/125

临时修复是定义自定义类型并使用类似于@Field(type="objectid")Document类的注释.

这是我用来完成此操作的自定义类型的代码.

/**
 * Custom Data type to support the MongoId data type in fields
 */
class ObjectId extends \Doctrine\ODM\MongoDB\Mapping\Types\Type
{
    public function convertToDatabaseValue($value)
    {
        if ($value === null) {
            return null;
        }
        if ( ! $value instanceof \MongoId) {
            $value = new \MongoId($value);
        }
        return $value;
    }

    public function convertToPHPValue($value)
    {
        return $value !== null ? (string)$value : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用注册

\Doctrine\ODM\MongoDB\Mapping\Types\Type::addType('objectid', 'ObjectId' );
Run Code Online (Sandbox Code Playgroud)