简体   繁体   English

Doctrine 如何搜索对象数组?

[英]Doctrine how to search array of objects?

I've array of objects我有对象数组

$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();

How can I check if $states contains object with data?如何检查$states包含带有数据的对象?

LocationState {#102960 ▼
  -id: 1
  -ident: "02"
  -name: "NAME"
  -country: LocationCountry {#102992 ▶}
}

This is no ArrayCollection but Array of Objects.这不是 ArrayCollection 而是对象数组。

For array of objects:对于对象数组:

$found = !empty(array_filter($objects, function ( $obj ) {
    return $obj->name == 'NAME' && $obj->id == 1;
}));

For ArrayCollection:对于 ArrayCollection:

$found = $objects->exists(function ( $obj ) {
    return $obj->name == 'NAME' && $obj->id == 1;
});

If you want them to be retrieved by the query:如果您希望通过查询检索它们:

$this->getDoctrine()->getRepository(LocationState::class)
  ->findBy(['name' => 'NAME', 'ident' => '02']);

If you just want to know if a specified object is on your collection, you will have to use some code如果您只想知道指定的对象是否在您的集合中,则必须使用一些代码

 $states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();

  $found = false;
  foreach($state in $states) {
    if($state->getName() == 'NAME' && $state->getIdent() == '02' ) {
      $found = true;
    }
  }

Doctrine 2 ArrayCollection filter method Doctrine 2 ArrayCollection 过滤方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM