search

Home  >  Q&A  >  body text

How to declare typed collections in Symfony entities in PHP 8.1

I get the error from PHPStan:

Property App\Entity\Product::$productArticles type mapping mismatch: property can contain Doctrine\Common\Collections\Collection but database  
         expects Doctrine\Common\Collections\Collection&iterable<App\Entity\ProductArticle>

My variable declaration:

#[ORM\OneToMany(mappedBy: 'product', targetEntity: ProductArticle::class)]
    /** @var  Collection<int, ProductArticle> */
    private Collection $productArticles;

How to use: annotation to declare ORM variables and PHPDoc annotation to declare Collection type at the same time?

P粉022723606P粉022723606270 days ago402

reply all(1)I'll reply

  • P粉014218124

    P粉0142181242024-02-18 10:42:11

    PHPDoc needs to be above the properties.

    class Foo
    {
        /** @var  Collection */
        #[ORM\OneToMany(mappedBy: 'product', targetEntity: ProductArticle::class)]
        private Collection $productArticles;
    }
    

    This is a bug in the parser library used by PHPStan (nikic/php-parser). So that has to be it now.

    reply
    0
  • Cancelreply