我在序列化已删除第一个元素的集合时遇到很多麻烦。
我有 CompaniesCollection 实体,与 Company 实体有 Many2Many 关系。
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Company")
* @Groups({"get-by-collection-owner"})
*/
private $items;
当我使用该集合获取对象时,我收到的项目是我首先添加的两个元素的数组。我将其序列化
{
"id": 19,
"name": "collection dummy name",
"items": [
{
"id": 431,
"name": "Company 1"
},
{
"id": 435,
"name": "Company 2"
}
],
"createdAt": "2019-03-11T13:55:43+01:00",
"updatedAt": "2019-03-11T15:48:57+01:00"
},
然后我删除第一项:
$collection->removeItem($companyToRemove);
$em = $this->getDoctrine()->getManager();
$em->persist($collection);
$em->persist($companyToRemove);
$em->flush();
$results = $companiesCollectionRepository->getCollections($companyLoader->getCurrentCompany());
序列化 $results 并获取不是一个元素的数组,而是具有前一个项目数组中第二个元素的键的对象:
{
"id": 19,
"name": "collection dummy name",
"items": {
"1": {
"id": 435,
"name": "Company 2"
}
},
"createdAt": "2019-03-11T13:55:43+01:00",
"updatedAt": "2019-03-11T15:52:48+01:00"
},
当我重新加载页面并获取该对象时,该集合又是一个元素数组,而不是一个对象。显然 Doctrine 不会从数据库获取新结果,而是返回已经加载到内存中的数据。
并且序列化器很可能将此“数组”视为“对象”,因为它的第一个数组元素的键不是以 0 开头,而是以键 1 开头。
有什么方法可以再次进行该查询,以便我获得新生成的密钥,或刷新这些密钥?
EDIT:
实际上我终于找到了简单的解决方案:刷新后刷新
$collection->removeItem($companyToRemove);
$em = $this->getDoctrine()->getManager();
$em->persist($collection);
$em->persist($companyToRemove);
$em->flush();
$em->refresh($collection);