ПЛАТФОРМА API «Невозможно создать IRI для объекта»

Я создал API, используя Symfony 6, и я делаю фильтры, используя платформу API. У меня 12 объектов работают отлично, но один выдает ошибку.

Это ошибка при выполнении запроса GET:

Unable to generate an IRI for \"App\\Entity\\Titols\"."

Это компания Титолс:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;

/**
 * Titols
 *
 * @ORM\Table(name = "obres")
 * @ORM\Entity
 */
#[ApiResource]
#[ApiFilter(SearchFilter::class, properties: ['titol' => 'partial'])]
class Titols implements \JsonSerializable
{
    /**
     * @var string
     *
     * @ORM\Column(name = "codi", type = "string", length=18, nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy = "IDENTITY")
     */
    private $codi;

    /**
     * @var string
     *
     * @ORM\Column(name = "titol", type = "string", length=75, nullable=false)
     */
    private $titol;

    /**
     * @var int
     *
     * @ORM\Column(name = "autor_id", type = "integer", nullable=false)
     */
    private $autorId = '0';

    /**
     * @var string
     *
     * @ORM\Column(name = "tipus", type = "string", length=10, nullable=false)
     */
    private $tipus;

    /**
     * @var string|null
     *
     * @ORM\Column(name = "data", type = "string", length=5, nullable=true, options = {"default" = "NULL"})
     */
    private $data = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "instrument", type = "string", length=75, nullable=true, options = {"default" = "NULL"})
     */
    private $instrument = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "dacomp", type = "text", length=65535, nullable=true, options = {"default" = "NULL"})
     */
    private $dacomp = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "enreg", type = "text", length=65535, nullable=true, options = {"default" = "NULL"})
     */
    private $enreg = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "partitu", type = "string", length=17, nullable=true, options = {"default" = "NULL"})
     */
    private $partitu = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "partice", type = "string", length=17, nullable=true, options = {"default" = "NULL"})
     */
    private $partice = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "pdf1", type = "string", length=50, nullable=true, options = {"default" = "NULL"})
     */
    private $pdf1 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "pdf2", type = "string", length=50, nullable=true, options = {"default" = "NULL"})
     */
    private $pdf2 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "pdf3", type = "string", length=50, nullable=true, options = {"default" = "NULL"})
     */
    private $pdf3 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "notes1", type = "string", length=255, nullable=true, options = {"default" = "NULL"})
     */
    private $notes1 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "notes2", type = "string", length=255, nullable=true, options = {"default" = "NULL"})
     */
    private $notes2 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "mp3", type = "string", length=50, nullable=true, options = {"default" = "NULL"})
     */
    private $mp3 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "uri_spotify", type = "string", length=255, nullable=true, options = {"default" = "NULL"})
     */
    private $uriSpotify = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "notes3", type = "string", length=255, nullable=true, options = {"default" = "NULL"})
     */
    private $notes3 = 'NULL';

    /**
     * @var string|null
     *
     * @ORM\Column(name = "notes4", type = "string", length=255, nullable=true, options = {"default" = "NULL"})
     */
    private $notes4 = 'NULL';

    /**
     * @var int|null
     *
     * @ORM\Column(name = "arranjador_id", type = "integer", nullable=true, options = {"default" = "NULL"})
     */
    private $arranjadorId = NULL;


    public function getId(): ?string
    {
        return $this->codi;
    }

    public function setId(string $codi): self
    {
        $this->codi = $codi;

        return $this;
    }

    public function getCodi(): ?string
    {
        return $this->codi;
    }

    public function setCodi(string $codi): self
    {
        $this->codi = $codi;

        return $this;
    }

    public function getTitol(): ?string
    {
        return $this->titol;
    }

    public function setTitol(string $titol): self
    {
        $this->titol = $titol;

        return $this;
    }

    public function getAutorId(): ?int
    {
        return $this->autorId;
    }

    public function setAutorId(int $autorId): self
    {
        $this->autorId = $autorId;

        return $this;
    }

    public function getTipus(): ?string
    {
        return $this->tipus;
    }

    public function setTipus(string $tipus): self
    {
        $this->tipus = $tipus;

        return $this;
    }

    public function getData(): ?string
    {
        return $this->data;
    }

    public function setData(?string $data): self
    {
        $this->data = $data;

        return $this;
    }

    public function getInstrument(): ?string
    {
        return $this->instrument;
    }

    public function setInstrument(?string $instrument): self
    {
        $this->instrument = $instrument;

        return $this;
    }

    public function getDacomp(): ?string
    {
        return $this->dacomp;
    }

    public function setDacomp(?string $dacomp): self
    {
        $this->dacomp = $dacomp;

        return $this;
    }

    public function getEnreg(): ?string
    {
        return $this->enreg;
    }

    public function setEnreg(?string $enreg): self
    {
        $this->enreg = $enreg;

        return $this;
    }

    public function getPartitu(): ?string
    {
        return $this->partitu;
    }

    public function setPartitu(?string $partitu): self
    {
        $this->partitu = $partitu;

        return $this;
    }

    public function getPartice(): ?string
    {
        return $this->partice;
    }

    public function setPartice(?string $partice): self
    {
        $this->partice = $partice;

        return $this;
    }

    public function getPdf1(): ?string
    {
        return $this->pdf1;
    }

    public function setPdf1(?string $pdf1): self
    {
        $this->pdf1 = $pdf1;

        return $this;
    }

    public function getPdf2(): ?string
    {
        return $this->pdf2;
    }

    public function setPdf2(?string $pdf2): self
    {
        $this->pdf2 = $pdf2;

        return $this;
    }

    public function getPdf3(): ?string
    {
        return $this->pdf3;
    }

    public function setPdf3(?string $pdf3): self
    {
        $this->pdf3 = $pdf3;

        return $this;
    }

    public function getNotes1(): ?string
    {
        return $this->notes1;
    }

    public function setNotes1(?string $notes1): self
    {
        $this->notes1 = $notes1;

        return $this;
    }

    public function getNotes2(): ?string
    {
        return $this->notes2;
    }

    public function setNotes2(?string $notes2): self
    {
        $this->notes2 = $notes2;

        return $this;
    }

    public function getMp3(): ?string
    {
        return $this->mp3;
    }

    public function setMp3(?string $mp3): self
    {
        $this->mp3 = $mp3;

        return $this;
    }

    public function getUriSpotify(): ?string
    {
        return $this->uriSpotify;
    }

    public function setUriSpotify(?string $uriSpotify): self
    {
        $this->uriSpotify = $uriSpotify;

        return $this;
    }

    public function getNotes3(): ?string
    {
        return $this->notes3;
    }

    public function setNotes3(?string $notes3): self
    {
        $this->notes3 = $notes3;

        return $this;
    }

    public function getNotes4(): ?string
    {
        return $this->notes4;
    }

    public function setNotes4(?string $notes4): self
    {
        $this->notes4 = $notes4;

        return $this;
    }

    public function getArranjadorId(): ?int
    {
        return $this->arranjadorId;
    }

    public function setArranjadorId(?int $arranjadorId): self
    {
        $this->arranjadorId = $arranjadorId;

        return $this;
    }

    public function jsonSerialize()
    {
        return [
            "codi" => $this->getCodi(),
            "titol" => $this->getTitol(),
            "autor_id" => $this->getAutorId(),
            "tipus" => $this->getTipus(),
            "data" => $this->getData(),
            "instrument" => $this->getInstrument(),
            "dacomp" => $this->getDacomp(),
            "enreg" => $this->getEnreg(),
            "partitu" => $this->getPartitu(),
            "partice" => $this->getPartice(),
            "pdf1" => $this->getPdf1(),
            "pdf2" => $this->getPdf2(),
            "pdf3" => $this->getPdf3(),
            "notes1" => $this->getNotes1(),
            "notes2" => $this->getNotes2(),
            "mp3" => $this->getMp3(),
            "uri_spotify" => $this->getUriSpotify(),
            "notes3" => $this->getNotes3(),
            "notes4" => $this->getNotes4(),
            "arranjador_id" => $this->getArranjadorId()
        ];
    }
}

Это единственная сущность, которая у меня есть, где идентификатор - это не число, а строка, может ли это быть проблемой?

Это функция getAll в TitolsController.php для сохранения данных:

    /**
     * @Route("/api/titols", methods = {"GET"})
     */
    public function getAll(TitolsRepository $titolsRepository): Response
    {
        $this->denyAccessUnlessGranted(TitolsVoter::VIEW);

        $titols = $titolsRepository->findBy([], ['codi' => 'ASC'], 10);

        return $this->json($titols);
    }

Здравствуйте, какой у вас запрос GET?

Gary Houbre 28.03.2022 17:07

Привет @GaryHoubre, я обновил вопрос. Но дело в том, что GET-запрос работает отлично, когда я комментирую все use ApiPlatfrom ..., а также #[ApiResource] #[ApiFilter]. Я думаю, что-то об идентификаторе, который не нравится платформе API

S.Marx 28.03.2022 22:17

Почему у вас есть собственный контроллер? Когда вы делаете именно какой запрос, вы получаете сообщение об ошибке?

yivi 29.03.2022 10:52

Я просматриваю вашу проблему, у меня есть вопрос, почему пользовательский контроллер? Если вы удалите свою функцию getAll, можете ли вы повторить тот же запрос GET?

Gary Houbre 29.03.2022 10:55

@yivi У меня есть собственный контроллер для создания запросов API (GET, POST, DELETE, PUT), затем я нашел платформу API, поэтому использую ее для создания фильтрации. Я получаю сообщение об ошибке, когда делаю запрос GET. Дело в том, что если я прокомментирую #[ApiResource] and #[ApiFilter(SearchFilter::class, properties: ['titol' => 'partial'])], я не получаю никакой ошибки, поэтому я знаю, что это должно быть что-то о платформе id и API.

S.Marx 29.03.2022 11:05

@GaryHoubre Ответ пользовательского контроллера такой же, как тот, на который я ответил yivi, и нет, если я удалю функцию getAll, она не будет работать.

S.Marx 29.03.2022 11:07

Используя пользовательский контроллер, вы ломаете вещи, особенно то, как вы его используете. Api-Platform уже имеет встроенные фильтры поиска и фильтры заказов. Удалите его и устраните проблему, не используя собственный контроллер.

yivi 29.03.2022 11:09

Я попробую. Но все остальные объекты с пользовательскими контроллерами, а затем с использованием платформы API для создания фильтров работают отлично. Это не работает, потому что это сущность без id, а id вместо этого называется codi. Это то, о чем я спрашивал, могу ли я использовать коди в качестве идентификатора без жалоб на платформу API.

S.Marx 29.03.2022 11:16

Да, ты можешь. Но ваш вопрос обрывается не через API-платформу, а фактически через какой-то пользовательский контроллер, который даже не объявлен в аннотации ресурса. Просто избавьтесь от него, попробуйте конечные точки и все должно работать из коробки.

yivi 29.03.2022 11:18
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
2
9
68
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

В конце концов, я не использовал собственный контроллер, который у меня был, и добавил GET request, как указано в документации платформы API:

#[ApiResource(
    attributes: ["security" => "is_granted('PERMISSION_TITOL')"],
    collectionOperations: [
        'get' => ['method' => 'get'],
    ],
    itemOperations: [
        'get' => [
            'path' => '/api/titols'            
        ],
    ],
)]

Это решило ошибку Unable to generate an IRI for \"App\\Entity\\Titols\"."

Другие вопросы по теме