Set Embeddable Field as Primary Key from Parent Entity Mapping - Doctrine2
Asked Answered
C

1

20

TLDR; Doctrine2: I need to know if it is possible to make a field within an Embeddable into a Primary Key from the Parent Entities (or MappedSuperclass') mapping. I already know how to set the primary key from the Embeddable's mapping, but this is not ideal (see "The Long Version").

The Long Version; I am trying to create Identity Value Objects for my Entities using Doctrine2 Embeddables.

Here is my problem...

  • I have two different Embeddables (MyEntityId and OtherEntityId) in an Entity (MyEntity).

  • I want a field within MyEntityId to be MyEntity's primary key.

  • As I have two identity embeddables in the same entity I want to define the primary key field in the entity mapping file rather than the embeddable mapping.

  • If I define the Primary Key from within the embeddable I run into problems when I want to do the same for OtherEntityId (as I am using it elsewhere).

  • Mapping the primary key in MyEntityId and OtherEntityId leads to MyEntity having a composite key, which I don't want.

Here are my mappings at the moment...

MyEntity:
    embedded:
        MyEntityId:
            class: 'MyEntityId'
            columnPrefix: false
        OtherEntityId:
            class: 'OtherEntityId'
            columnPrefix: false

MyEntityId:
    type: 'embeddable'
        id: 
            id:
                column: 'MyEntityId'
                type: 'string'

OtherEntityId:
    type: 'embeddable'
        id: 
            id:
                column: 'OtherEntityId'
                type: 'string'

Solutions?

  • Create two seperate Embeddables to represent the same Id Value Object (not very dry and too complex)

  • Map the Embeddable's Primary Key field from the entity (is this possible? I can't find it anywhere in documentation)

Cammi answered 9/8, 2014 at 16:27 Comment(1)
Still no solution for this. I ran into same problem. It would be very good to point the Embedded object's column id from the Entity that maps it, to make the Embedded field part of primary key in DB table.Aubreir
Q
0

I use Doctrine Types https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/cookbook/custom-mapping-types.html#custom-mapping-types instead of Embeddables to implement this, so for each ID in the system I have a separate type. It's a bit of extra code, but at least I only have one VO for each ID.

With types you can implement your entities like this:

class Post
{
    #[ORM\Id]
    #[ORM\Column(name: 'id', type: 'PostId')]
    private PostId $postId;

    #[ORM\Column(type: 'UserId')]
    private UserId $userId;
}
Qualify answered 9/12, 2022 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.