Doctrine赋值错误:无法将Doctrine\ORM\PersistentCollection分配给属性。

15

我有一个上传功能,想从数据库中显示所有类别,但遇到了EntityType错误,不知道为什么以前是好的。

这是错误信息:Cannot assign Doctrine\ORM\PersistentCollection to property App\Entity\Category::$posts of type Doctrine\Common\Collections\ArrayCollection

<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CategoryRepository::class)
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private int $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private string $name;

    /**
     * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
     */
    private ArrayCollection $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 gePosts(): Collection
    {
        return $this->posts;
    }

    public function addPost(Post $post): self
    {
        if (!$this->posts->contains($post)) {
            $this->$posts[] = $posts;
            $post->setCategoryId($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->getCategoryId() === $this) {
                $post->setCategoryId(null);
            }
        }

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

上传表单,我在这里遇到了错误。

<?php

declare(strict_types=1);

namespace App\Form\Post;

use App\Entity\Category;
use App\Entity\Post;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;

class UploadType extends AbstractType
{
    /**
     * @param \Symfony\Component\Form\FormBuilderInterface $builder
     * @param array                                        $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a valid Title. '
                    ])
                ]
            ])
            ->add('category', EntityType::class, [
                'mapped' => false,
                'class' => Category::class,
                'choice_label' => 'name',
                'expanded' => true
            ])
            ->add('poster', FileType::class, [
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '6000K',
                        'mimeTypes' => [
                            'image/x-png',
                            'image/jpeg',
                        ],
                        'mimeTypesMessage' => 'Please upload a image file.'
                    ])
                ]
            ])
            ->add('description', TextareaType::class, [
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a valid Title. '
                    ])
                ]
            ])
            ->add('mediainfo', TextareaType::class, [
                'required' => false,
            ]);
    }
    
    /**
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Post::class,
        ]);
    }
}

在Post实体中。
   /**
     * @ORM\ManyToOne(targetEntity=Category::class, inversedBy="posts")
     */
    private Category $Category_id;

环境信息:

  • Symfony 5.2.5 (env: dev, debug: true)
  • PHP 版本: 8.0.3
  • 数据库驱动及版本: 8.0.23-0ubuntu0.20.04.1
4个回答

36

经过一番搜索,我找到了答案,将ArrayCollection更改为Collection解决了我的问题。

更改:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private \Doctrine\Common\Collections\ArrayCollection $posts;

收件人:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private \Doctrine\Common\Collections\Collection $posts;

2
今天是2021年11月4日,你刚刚拯救了我从无眠的夜晚中。非常感谢@kunwara,这让我的一天变得美好了! - Olasunkanmi

8
问题在于类型提示(ArrayCollection => Collection)。
更改为:
/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private ArrayCollection $Posts;

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

通过:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private Collection $Posts;

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

2

$this->$posts[] = $posts;

应该改为:

$this->$posts[] = $post;


1
private ArrayCollection $posts;

是 Doctrine 的直接依赖项:

use Doctrine\Common\Collections\ArrayCollection;

如果您不同意,可能是因为它违反了SOLID中的“D”,请尝试使用纯PHP伪类型Iterable(https://www.php.net/manual/en/language.types.iterable.php),像这样:

private iterable $posts;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接