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

问题描述 投票:3回答:1

我的对象“字段”:

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 ▶}
]

我想知道“fields”中是否存在某个“templateId”:

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

结果是“假的”,即使我认为它是真的。

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

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

arrays symfony oop arraycollection
1个回答
4
投票

首先,

$templateId = $field->getTemplate();

返回一个TemplateCollection模板(顺便说一句,你应该重命名你的属性模板)

我相信你想要做的是检查一个模板是否在Fields的数组模板中。

所以有两种正确的方法:

使用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);

比较索引/键:

$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;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.