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

时间:2019-04-15 11:35:29

标签: arrays symfony oop arraycollection

我的对象“字段”:

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”:

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

即使我希望结果为true,结果也为“ false”。

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

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

1 个答案:

答案 0 :(得分:4)

首先

$templateId = $field->getTemplate();

返回模板的ArrayCollection(通过这种方式应重命名属性“模板”)

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

因此,有两种适当的方法可以做到:

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