【问题标题】:API PLATFORM custom identifier in parent class/table父类/表中的 API PLATFORM 自定义标识符
【发布时间】:2020-10-16 11:19:18
【问题描述】:

我有使用继承映射原则继承的实体。我有一个使用@ORM\PrePersist() 生成的自定义标识符,它在一个特征中,并且在父类中使用。

我希望能够更新子类具有的属性,因此,我需要在子实体上运行端点

运行item操作时,api平台找不到资源。

PATCH /api/childas/{hash}

NotFoundHttpException Not Found

api 平台,它不将哈希识别为标识符。以 id 作为你的标识,即使它是 false 并且 hash 是 true。

生成用于识别资源的哈希的特征

<?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));
    }
}

父类,是存储哈希的表

<?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
}

子类,我要对其执行操作,例如更新属于该类的某些属性

<?php

namespace App\Entity;


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

为实体Child配置api平台操作

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

我曾考虑过使用数据提供程序,但我不断收到错误消息。

【问题讨论】:

    标签: symfony doctrine-orm api-platform.com


    【解决方案1】:

    错误是因为 trait 中的 hash 属性和父实体中的 id 属性都必须可以从要使用的实体访问。

    Doctrine ORM 使用反射类来获取有关属性及其注释的信息。 ReflectionClass::hasProperty 显然不允许查看父类中的私有属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 2018-09-03
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多