我试图根据Doctrine和PHPStan使用正确的类型,但是,对于实体关系,我似乎无法纠正它。
我使用的是PHP8.1.6、Doctrine2.6.3、PHPStan 1.7.3和PHPStan/Doctrine1.3.6。
我的实体看起来是这样的
#[ORM\Entity]
class Thing
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(options: ['unsigned' => true])]
private ?int $id;
#[ORM\Column]
private string $name;
/** @var Collection&iterable<Item> $items */
#[ORM\OneToMany(mappedBy: 'thing', targetEntity: Item::class)]
private Collection $items;
public function getId(): ?int
{
return $this->id;
}
/**
* @return iterable<Items>
*/
public function getItems(): iterable
{
return $this->items;
}
}对于ID,这不是抱怨(原则规则被加载到PHPStan中,它工作得很好)。然而,对于$items集合来说,它说的是“从不写,只读”。这是没有意义的,因为它是一个集合,不会被写入(而是通过它的方法添加到其中)。
我不太明白为什么它给我这个错误,我似乎找不到很多关于它,除了“它应该工作”。
发布于 2022-05-29 16:36:16
对于该私有财产,您没有“设置器”或“加法器/移除器”。所以,PhpStan确实是对的。
要么从该关系的反转侧(也就是在Thing类中)完全删除该属性,要么添加一些“加法器/移除器”。
这通常是这样的。
public function addItem(Item $item): self
{
if (!$this->items->contains($items)) {
$this->items[] = $item;
// optional but keeps both sides in sync
$item->setThing($this);
}
return $this;
}
public function removeItem(Item $item): self
{
$this->items->removeElement($item);
// should your Item::thing be not nullable, skip this
$item->setThing(null);
return $this;
}https://stackoverflow.com/questions/72423873
复制相似问题