Doctrine如何搜索对象数组?

时间:2018-01-22 17:20:15

标签: symfony doctrine-orm

我有一些对象

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

如何检查$states是否包含带数据的对象?

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

这不是ArrayCollection而是Array of Objects。

2 个答案:

答案 0 :(得分:0)

如果您希望查询检索它们:

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

如果您只想知道集合中是否有指定的对象,则必须使用一些代码

 $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

答案 1 :(得分:0)

对于对象数组:

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

对于ArrayCollection:

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