Search code examples
phpmongodbsymfonydoctrinedoctrine-odm

Symfony, ODM: how to set multiply ids annotation


So the question is how to provide two or more identifiers keys? I couldn't find any answers on this question in google search... Here is example:

class Customer
{
    /**
     * @ODM\Id
     *
     * @JMS\Expose
     * @JMS\Type("string")
     *
     */
    protected $id;

    /**
     * @var integer
     * @ODM\Id(strategy="INCREMENT")
     *
     * @JMS\Expose
     * @JMS\Type("integer")
     *
     */
    protected $customerId;

So in this case I have second id which increment as I wrote, but first id became null. If I remove and write just * @ODM\Field(type="integer") everything is ok, but no increment of customerId. So how can I have to ids in document? Or I'm wrong and I don't do this?


Solution

  • Identifier is automatically mapped as _id field therefore there can be only 1 field mapped as @Id.

    Done similar things in the past and I'd suggest keeping \MongoId as document identifier and generating incremented customerId in your code instead of relying on ODM to do so. Making such generator is pretty straightforward, you need to hook into persisting document (be it in your domain code, which I advice, or leveraging prePersist event) and write generator similar to ODM's IncrementGenerator.