开发者

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

开发者 https://www.devze.com 2023-03-19 10:33 出处:网络
I want to store references manually instead of letting the ODM use the DBRef type. I have the option of storing the _id I want to reference as a @String (for e.g - \"4e18e625c2749a260e000024\" ), but

I want to store references manually instead of letting the ODM use the DBRef type.

I have the option of storing the _id I want to reference as a @String (for e.g - "4e18e625c2749a260e000024" ), but how do I store an instance of an ObjectId in this field instead?

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

Saving it using a MongoId object instead of a string wil开发者_如何学编程l save me half the space on this field. It's the same data type used by the @Id annotation, but the @Id can be used just once in a 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. 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).


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

A temporary fix would be to define a custom type and use an annotation like @Field(type="objectid") in your Document classes.

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") */
0

精彩评论

暂无评论...
验证码 换一张
取 消