1

Suppose we have the following documents with relationship between them:

/**
 * @ODM\Document(collection="foo")
 */
class Foo
{
    /** @ODM\Id(name="_id", strategy="NONE", type="string") */
    public $id;

    /** @ODM\Field(name="name", type="string") */
    public $name;

    /**
     * @ODM\ReferenceOne(targetDocument="Bar")
    */
    public $bar;
}


/**
 * @ODM\Document(collection="bar")
 */
class Bar
{
    /** @ODM\Id(name="_id", strategy="NONE", type="string") */
    public $id;

    /** @ODM\Field(name="name", type="string") */
    public $name;
}

And the following code:

$foo = new Foo();
$foo->id = uniqid();
$foo->name = 'thefoo';

$bar = new Bar();
$bar->id = uniqid();
$bar->name = 'thebar';
$foo->bar = $bar;

$dm->persist($bar);
$dm->persist($foo);
$dm->flush();

In this case the relation to "Bar" will be stored in mongo in dbRefs format.

{
    "_id" : "58ac22815e49d",
    "name" : "thefoo",
    "bar" : {
        "$ref" : "bar",
        "$id" : "58ac22815e59a",
        "$db" : "mydb"
    }
}

However what I'm trying to do is to store the relationship "manually" in this format:

{
    "_id" : "58ac22815e49d",
    "name" : "thefoo",
    "bar_id" : "58ac22815e59a"
}

Is there a way in Doctrine ODM that I can map my documents to store the relationships in such format?

Edit: Thanks to malarzm's answer I achieved the desired result with the following mapping.

/**
 * @ODM\Document(collection="foo")
 */
class Foo
{
    /** @ODM\Id(name="_id", strategy="NONE", type="string") */
    public $id;

    /**
     * @ODM\ReferenceOne(name="bar_id", targetDocument="Bar", storeAs="id")
     */
    public $bar;

    /** @ODM\Field(name="name", type="string") */
    public $name;
}
Community
  • 1
  • 1
memo
  • 273
  • 2
  • 15

1 Answers1

2

For ODM to store only id of referenced document you need to add storeAs="id" to your reference mapping, for more informations please see Storing References chapter in documentation.

malarzm
  • 2,831
  • 2
  • 15
  • 25
  • Thanks for the answer. It works exactly as I wanted! – memo Feb 22 '17 at 07:31
  • @malarzm what if we do not add any mapping or reference like "ReferenceOne" and instead that we simply make it a string type field then will it be more near to manaul reference as MongoDB doc suggests? Is that good or "storeAs" is also good? – Azam Alvi Sep 05 '22 at 07:09
  • @AzamAlvi without ReferenceOne the field will be just a string, nothing more. With ReferenceOne and storeAs you're storing a string and get a document/proxy thanks to ODM. – malarzm Sep 07 '22 at 16:40