【发布时间】:2021-03-15 12:19:21
【问题描述】:
嘿,使用带有 GeoData 属性的 Doctrine ORM
/**
* @var GeoData[]|Collection
*
* @ORM\ManyToMany(targetEntity="Acme\Bundle\CoreBundle\Entity\GeoData", inversedBy="addresses", cascade="persist", fetch="LAZY")
* @ORM\JoinTable(name="users__addresses_geodata")
*/
protected $geoData;
并使用特殊的 getter 来获取 GeoData 的第一个元素
public function getMostLocalGeoDatum(): ?GeoData
{
if (null == $this->geoData && $this->geoData->isEmpty()){
return null;
}
/** @var GeoData $localeGeoDatum */
$localeGeoDatum = $this->geoData->first();
return $localeGeoDatum;
}
但是每次我使用这个 getter 时,我都会收到一个错误:
TypeError: Return value of ACME\Bundle\CoreBundle\Entity\Address::getMostLocalGeoDatum() must be an instance of ACME\Bundle\CoreBundle\Entity\GeoData or null, boolean returned
任何线索可能是错误的?根据 Doctrine ArrayCollection 文档,first() 应该返回 ArrayCollection 的第一个元素。
【问题讨论】:
-
这条线
if (null == $this->geoData && $this->geoData->isEmpty())正确吗?首先验证 geoData 是否为空,然后验证其是否为空(但仅当 geoData 为空时)。这应该会产生意想不到的行为,我相信我猜if (is_null($this->geoData) || ($this->geoData->isEmpty())效果更好......也许 -
first()内部使用reset,当数组为空时返回false。所以像 Gowire 建议的那样修复你的状况应该可以解决这个问题。 -
如果您查看
first的真实签名,您会看到它被标记为返回结果或false。 -
最好的,谢谢明确指正!
标签: php doctrine arraycollection