Symfony 4 - 具有ManyToMany关系的对象序列化



我有两个实体:Acquistion & priceHistory。 它们具有以下多对多关系:

征用.php

....
/**
* @ORMManyToMany(targetEntity="AppEntityPriceHistory", inversedBy="acquisitions")
* @MaxDepth(1)
*/
private $services;
public function __construct()
{
$this->services = new ArrayCollection();
....
}
/**
* @return Collection|ServicePrice[]
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(ServicePrice $service): self
{
if (!$this->services->contains($service)) {
$this->services[] = $service;
}
return $this;
}
public function removeService(ServicePrice $service): self
{
if ($this->services->contains($service)) {
$this->services->removeElement($service);
}
return $this;
}

历史价格.php

/**
* @ORMManyToMany(targetEntity="AppEntityAcquisition", mappedBy="services")
*/
private $acquisitions;
public function __construct(){
$this->acquisitions = new ArrayCollection();
}
/**
* @return Collection|Acquisition[]
*/
public function getAcquisitions(): Collection
{
return $this->acquisitions;
}
public function addAcquisition(Acquisition $acquisition): self
{
if (!$this->acquisitions->contains($acquisition)) {
$this->acquisitions[] = $acquisition;
$acquisition->addService($this);
}
return $this;
}
public function removeAcquisition(Acquisition $acquisition): self
{
if ($this->acquisitions->contains($acquisition)) {
$this->acquisitions->removeElement($acquisition);
$acquisition->removeService($this);
}
return $this;
}

它工作正常,架构已正确创建,实体持久化等。

但是我想序列化和反序列化 Acquiisition 对象,如下所示:

$encoders = array(new JsonEncoder());
$objectNormalizer = new ObjectNormalizer(); 
$objectNormalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$normalizers = array(new DateTimeNormalizer(), $objectNormalizer);
$serializer = new Serializer($normalizers, $encoders);
$tempCart = new Acquisition();
$service_prices = $this->getDoctrine()->getRepository(ServicePrice::class)->findAll()[0];
$tempCart->addService($service_prices);
$jsonContent = $serializer->serialize($tempCart, 'json');

这给了我以下错误:

Type error: Return value of AppEntityPriceHistory::getAcquisitions() must be an instance of DoctrineCommonCollectionsArrayCollection, instance of DoctrineORMPersistentCollection returned

我该如何解决这个问题?

非常感谢您的帮助。

皮尔

getAcquisitions()方法中的返回类型提示错误,它应该是Collection的(ArrayCollection实现(。

你可以试试,

/**
* @ORMManyToMany(targetEntity="AppEntityAcquisition", mappedBy="services")
*
* @ORMJoinTable(name="relation_table_name")
*
*/
private $acquisitions;

相关内容

  • 没有找到相关文章

最新更新