Search code examples
phpmongodbsymfonydoctrine-ormdoctrine-odm

Unidirectional many-to-one relation in Doctrine MongoDB ODM without MongoId


I'm trying to port the following Doctrine ORM example to Doctrine ODM.

<?php
/** @Entity */
class User
{
    /**
     * @ManyToOne(targetEntity="Address")
     * @JoinColumn(name="address_id", referencedColumnName="address_id")
     */
     private $address;
}

/** @Entity */
class Address
{
    // ...
}

I'm looking for the counterpart of @JoinColumn(), which I couldn't find in the documentation. Basically, I want to set the referencing field name and the referenced field name myself. How can I do this?


Solution

  • In MongoDB you can only reference by id, but you're not limited to using MongoID's. In fact, you can use whatever you like, including objects as id's.

    This is what you should do in MongoODM, to have a property of Address act as id and User will reference Address by the value of that field. You should also set simple=true for the reference.

    /**
     * @Document
     */
    class User
    {
        /**
         * @ReferenceOne(targetDocument="Address", simple=true)
         */
        protected $address;
    }
    
    /**
     * @Document
     */
    class Address
    {
        /**
         * @Id(strategy="NONE")
         */
        protected $someProperty;
    }
    

    Remember that if you change the value of that property in any of the addresses that are referenced by one or more users, that reference will become corrupt and cause some painful errors in doctrine ODM.