简体   繁体   中英

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?

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

This is no ArrayCollection but Array of Objects.

For array of objects:

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

For 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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