Core: Composite identifiers don't work

Created on 22 Sep 2015  路  6Comments  路  Source: api-platform/core

Hi,

I have an entity which uses composite identifiers:

class UserPreference
{
    /**
     * Defines the key of the user preference
     * @ORM\Column(type="string",length=255)
     * @ORM\Id
     *
     * @Groups({"default"})
     *
     * @var string
     */
    private $preferenceKey;

    /**
     * Defines the value. Note that the value is internally stored as a serialized string.
     *
     * @ORM\Column(type="text")
     *
     * @Groups({"default"})
     * 
     * @var mixed
     */
    private $preferenceValue;

    /**
     * Defines the user
     * @ORM\ManyToOne(targetEntity="PartKeepr\AuthBundle\Entity\User")
     *
     * @ORM\Id
     * @var \PartKeepr\AuthBundle\Entity\User
     */
    private $user;

When attempting to use it, I receive the following error:

The class \PartKeepr\AuthBundle\Entity\\UserPreference has no identifier.

I assume that it's hard to implement composite identifiers, so I propose to change the exception message to reflect that, something like "Composite identifiers detected, unable to use".

question

Most helpful comment

Actually by providing a DataProvider it works just fine :).

Maybe could you add a sample here? :-)

All 6 comments

It's a design choice to not allow composite id. A workaround is to add a custom method like the following:

public function getId()
{
    return $referenceKey.'-'.$user;
}

You'll also need a custom DataProvider.

The error message looks good to me because it can be thrown when an entity has no identifier at all.

Using the dev-master, we used an item query extension in order to achieve this at the DataProvider level.

@dunglas Unfortunately the message did not shed any light for me. Identifier is a pretty generic term and the first thing I did was looking in my entity if it had an identifier, and yes it had. So I read the code in the ApiBundle, which usually shouldn't be necessary. Maybe this message would clear confusion:

"The class \PartKeepr\AuthBundle\Entity\UserPreference has no identifier. Maybe you forgot to define the Identifier, or using composite identifiers?"

Also, I think it should be documented, if not done already.

Note, this issue is more about documentation than implementation, I solved it differently.

:+1: for your new message.

Is there a reason why composite identifiers are not supported?

Actually by providing a DataProvider it works just fine :).

Actually by providing a DataProvider it works just fine :).

Maybe could you add a sample here? :-)

Was this page helpful?
0 / 5 - 0 ratings