Carlos 2V
Carlos 2V

Reputation: 175

API PLATFORM custom identifier in parent class/table

I have entities that make use of Inheritance Mapping Doctrine inheritance. I have a custom identifier that I generate with @ORM\PrePersist(), which is in a trait and this is used in the parent class.

I want to be able to update properties that the child class has, for this reason, I need to run endpoints on the child entity

When I run an item operation, api platform can't find the resource.

PATCH /api/childas/{hash}

NotFoundHttpException Not Found

api platform, it doesn't recognize hash as identifier. Take the id as your identified, even if it is false and hash is true.

Trait to generate hashes with which I identify the resource

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;

trait HashableTrait
{
    /**
     * @ORM\Column(type="string", length=255)
     * @ApiProperty(identifier=true)
     */
    private $hash;

    public function getHash(): ?string
    {
        return $this->hash;
    }

    /**
     * @ORM\PrePersist()
     */
    public function setHash()
    {
        $this->hash = \sha1(\random_bytes(10));
    }
}

Parent class, is the table where the hash will be stored

<?php

namespace App\Entity;

use App\Entity\HashableTrait;

/**
 * @ORM\HasLifecycleCallbacks()
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="integer")
 * @ORM\DiscriminatorMap({
 *  1 = "App\Entity\ChildA",
 *  2 = "App\Entity\ChildB"
 * })
 */
class Parent
{
    use HashableTrait;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @ApiProperty(identifier=false)
     */
    private $id;

    public function getId(): ?int
    {
        return $this->id;
    }

    // Properties, setters, getters
}

Child class, on which I want to perform operations, such as updating some property that belongs to this class

<?php

namespace App\Entity;


class ChildA extends Parent
{
   // Custom properties for ChildA
}

Config api platform operations for entity Child

App\Entity\ChildA:
    collectionOperations:
        post: ~
    itemOperations:
        post: ~
        get: ~
        patch: ~
        delete: ~

I have thought about using data providers, but I keep getting the error.

Upvotes: 0

Views: 1549

Answers (1)

Carlos 2V
Carlos 2V

Reputation: 175

The error was because both the hash property in the trait and the id property in the parent entity must be accessible from the entity to use.

Doctrine ORM uses reflection class to get information about attributes and their annotations. ReflectionClass::hasProperty obviously does not allow viewing private properties in the parent class.

Upvotes: 1

Related Questions