【问题标题】:How can I check if a value exists in my Object PersistantCollection?如何检查我的 Object PersistantCollection 中是否存在值?
【发布时间】:2019-04-15 11:35:28
【问题描述】:

我的对象“字段”:

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

    首先,

    $templateId = $field->getTemplate();
    

    返回一个模板的 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);
    

    比较索引/键:

    $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;
            }
        }
    

    【讨论】:

    • 谢谢。不完全是。在 ArrayCollection“模板”中,我有例如 4 个模板。都有不同的ID。 Somethimes (1,2,3,4) 有时只有 (1,2) 有时 (3) 等等。我需要检查每个字段是否包含 ID 为“3”的模板。你知道我的意思吗?
    • 不使用另一个循环也可以吗?例如 array_key_exists?
    • 如果我想通过“uuid”进行检查,例如我不能使用 containsKey
    猜你喜欢
    • 2014-11-25
    • 2016-01-24
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多