Symfony, ODM: how to set multiply ids annotation

2019-09-14 17:37发布

问题:

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?

回答1:

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.



回答2:

You can only have two key one of string the other integer as part of a composite key, as per this documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html

So try:

class Customer
{
    /**
     * @ODM\Id
     * @ORM\Column(name="id", type="string")
     *
     * @JMS\Expose
     * @JMS\Type("string")
     *
     */
    protected $id;

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

I think that should work for you.