Аргумент должен быть типа ?массив, заданная строка, вызывается в doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php Annotations/DocParser.php

#symfony #doctrine-orm #api-platform.com

Вопрос:

я не понимаю своей ошибки в API Plateform.

ДоктринаORMОтображениеManyToOne::__construct(): Аргумент #2 ($каскад) должен иметь тип ?массив, заданная строка, вызывается в /Users/charleslem/symfony/API-plateform-php-8/Api-plateform-php8-symfony5/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php на линии 944.

О какой ошибке в аргументах говорят. у меня нет указаний.

Это мой код:

Первая сущность:

 
namespace AppEntity;

use ApiPlatformCoreAnnotationApiResource;
use AppRepositoryPostRepository;
use DoctrineORMMapping as ORM;
use SymfonyComponentSerializerAnnotationGroups;
use SymfonyComponentValidatorConstraintsLength;

//read:collection pour lire une collection d'article
//read:item correspond à la lecture d'un seul item
/*ici je souhaite afficher les attributs title et slug quand je demande une collection d'article mais afficher 
    mais afficher en plus le contennu ainsi que la date quand je fais une requete d'un seul article
*/

/**
 * @ORMEntity(repositoryClass=PostRepository::class)
 */
#[ApiResource(
    normalizationContext:['groups'=> ['read:collection']],
    itemOperations:[
        'get' => [
            'normalization_context' => ['groups'=> ['read:collection', 'read:item', 'read:Post']],
        'put' => [
            'denormalization_context' => ['groups' => ['put:Post']],
            ],
        ],
    ],
)]
class Post
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    #[Groups(['read:collection'])]
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    #[
        Groups(['read:collection','put:Post']),
        Length(min:5, max:255),

    ]
    private $title;

    /**
     * @ORMColumn(type="string", length=255)
     */
    #[
    Groups(['read:collection','put:Post']),
    Length(min:5, max:255),
    ]
    private $slug;

    /**
     * @ORMColumn(type="text")
     */
    #[Groups(['read:item','put:Post'])]
    private $content;

    /**
     * @ORMColumn(type="datetime_immutable", nullable=true)
     */
    #[Groups(['read:item','put:Post'])]
    private $uptdatedAt;

    /**
     * @ORMManyToOne(targetEntity=Category::class, inversedBy="posts", cascade="persiste")
     */
    #[Groups(['read:item','write:Post'])
    ]
    private $category;

    public function __construct()
    {
        $this->createdAt = new DateTime();
        $this->uptdatedAt = new DateTime();
    }

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getUptdatedAt()
    {
        return $this->uptdatedAt;
    }

    public function setUptdatedAt(?DateTimeImmutable $uptdatedAt): self
    {
        $this->uptdatedAt = $uptdatedAt;

        return $this;
    }

    public function getCategory(): ?category
    {
        return $this->category;
    }

    public function setCategory(?category $category): self
    {
        $this->category = $category;

        return $this;
    }
}
 

И моя вторая сущность :

 
namespace AppEntity;

use ApiPlatformCoreAnnotationApiResource;
use AppRepositoryCategoryRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentSerializerAnnotationGroups;

/**
 * @ApiResource()
 * @ORMEntity(repositoryClass=CategoryRepository::class)
 */
class Category
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    #[Groups('read:Post')]
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    #[Groups('read:Post','write:Post')]
    private $name;

    /**
     * @ORMOneToMany(targetEntity=Post::class, mappedBy="category")
     */
    private $posts;

    public function __construct()
    {
        $this->posts = new ArrayCollection();
    }

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return Collection|Post[]
     */
    public function getPosts(): Collection
    {
        return $this->posts;
    }

    public function addPost(Post $post): self
    {
        if (!$this->posts->contains($post)) {
            $this->posts[] = $post;
            $post->setCategory($this);
        }

        return $this;
    }

    public function removePost(Post $post): self
    {
        if ($this->posts->removeElement($post)) {
            // set the owning side to null (unless already changed)
            if ($post->getCategory() === $this) {
                $post->setCategory(null);
            }
        }

        return $this;
    }
}
 

Ответ №1:

В своих аннотациях вы определяете ManyToOne отношение и пытаетесь установить cascade для параметра строковое значение:

 /**
 * @ORMManyToOne(targetEntity=Category::class, inversedBy="posts", cascade="persiste")
 */
 

Как ясно указано в ошибке, это должен быть массив:

 /**
 * @ORMManyToOne(targetEntity=Category::class, inversedBy="posts", cascade={"persist"})
 */