简体   繁体   English

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

[英]How do you store an ObjectId while using Doctrine MongoDB ODM?

I want to store references manually instead of letting the ODM use the DBRef type.我想手动存储引用而不是让 ODM 使用 DBRef 类型。

I have the option of storing the _id I want to reference as a @String (for eg - "4e18e625c2749a260e000024" ), but how do I store an instance of an ObjectId in this field instead?我可以选择将要引用的 _id 存储为 @String(例如 - "4e18e625c2749a260e000024" ),但是如何在此字段中存储ObjectId的实例呢?

new \MongoId("4e18e625c2749a260e000024") <-- what's the annotation for this type?

Saving it using a MongoId object instead of a string will save me half the space on this field.使用 MongoId object 而不是字符串保存它可以节省我一半的空间。 It's the same data type used by the @Id annotation, but the @Id can be used just once in a Document.它与 @Id 注释使用的数据类型相同,但 @Id 在 Document 中只能使用一次。

What' the right annotation to accomplish this?完成此操作的正确注释是什么?

Update: There's now an official support for this type.更新:现在有对这种类型的官方支持。 Use @ObjectId or @Field(type="object_id") in your annotation to use the ObjectId / MongoId type.在注释中使用@ObjectId@Field(type="object_id")以使用 ObjectId / MongoId 类型。 There's no need to use the solution below.无需使用以下解决方案。

Also, use the latest master code from github.com/doctrine/mongodb-odm and avoid using the version on the website (it's out-dated).另外,请使用来自 github.com/doctrine/mongodb-odm 的最新主代码,并避免使用网站上的版本(它已过时)。


Solution (deprecated)解决方案(已弃用)

Looks like there's no support for this yet.似乎还没有对此的支持。 I discussed this issue on the IRC channel and opened a ticket for it here: https://github.com/doctrine/mongodb-odm/issues/125我在 IRC 频道上讨论过这个问题,并在这里开票: https://github.com/doctrine/mongodb-odm/issues/125

A temporary fix would be to define a custom type and use an annotation like @Field(type="objectid") in your Document classes.临时解决方法是定义自定义类型并在 Document 类中使用@Field(type="objectid")类的注释。

Here's the code for the custom type I'm using to accomplish this.这是我用来完成此操作的自定义类型的代码。

/**
 * 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;
    }
}

Register it using注册它使用

\Doctrine\ODM\MongoDB\Mapping\Types\Type::addType('objectid', 'ObjectId' );

Try:尝试:

/** @Id(strategy="NONE") */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM