如何检查对象 PersistantCollection 中是否存在值?

How can I check if a value exists in my Object PersistantCollection?

我的对象"fields":

array:4 [▼
  0 => Fields {#10900 ▶}
  1 => Fields {#11222 ▶}
  2 => Fields {#11230 ▼
    -id: 8
    -name: "Tier"
    -uuid: "5f60107fe4"
    -productgroup: PersistentCollection {#11231 ▶}
    -options: PersistentCollection {#11233 ▶}
    -template: PersistentCollection {#11235 ▼
      -snapshot: []
      -owner: Fields {#11230}
      -association: array:20 [ …20]
      -em: EntityManager {#4288 …11}
      -backRefFieldName: "fields"
      -typeClass: ClassMetadata {#7714 …}
      -isDirty: false
      #collection: ArrayCollection {#11236 ▼
        -elements: []
      }
      #initialized: true
    }
    -type: Type {#11237 ▶}
    -formatstring: ""
  }
  3 => Fields {#11511 ▶}
]

我想知道某个"templateId"是否存在于"fields"中:

foreach ($fields as $field) {
  $templateId = $field->getTemplate();
  $result = property_exists($templateId, 3);    
}

结果是 "false",即使我希望它是真的。

实体字段列表:https://pastebin.com/zcuFi1dE

模板:https://pastebin.com/mVkKFwJr

首先,

$templateId = $field->getTemplate();

return 模板的 ArrayCollection(顺便说一下,您应该重命名 属性 模板)

我相信您想做的是检查模板是否在字段数组 模板 中。

所以有两种正确的方法:

使用 Doctrine\Common\Collections\ArrayCollection

中的 contains 方法

将一个对象与另一个对象进行比较

//First get the proper Template object instead of the id
$template = $entityManager->getRepository(Template::class)->find($templateId);
$templateArray = $field->getTemplate();

//return the boolean you want
$templateArray->contains($template);

比较indexes/keys:

$templateArray = $field->getTemplate();

//return the boolean you want
$templateArray->containsKey($templateId);

但如果你想做同样的事情,但使用另一个 属性 而不是你可以遍历你的数组的 id :

比较其他属性

//In our case, name for example
$hasCustomAttribute=false;
    foreach($field->getTemplate() as $template){
        if($template->getName() == $nameToTest){
            $hasCustomAttribute=true;
        }
    }