0

I am loading all entity types I need to update like below

$current_fruit = \Drupal::entityTypeManager()->getStorage('fruit')->loadByProperties(['status' => '1']);

Then I update them in a way that I loop through the object and if particular value is matched I update some properties.

Thing is I am wondering is it possible to not loop through all of them, but just use some "magic" get method to find entity within loaded entities and then updated it, or is the foreach best method to do this? Something like

$fruit = $current_fruit->name->getByValue("Apple);

and then I could just use

$fruit->set('price', $40);
$fruit->save();

1 Answer 1

0

You can actually use loadByProperties as that filter, you just need to extend your search:

$apples = \Drupal::entityTypeManager()
  ->getStorage('fruit')
  ->loadByProperties([
    'status' => '1', 
    'name' => 'Apple'
  ]);

If you need to filter an existing, broader list, then just use foreach, array_filter, etc; Drupal doesn't have any special methods for it.

2
  • Was thinking this would be loading entites too many times. Like it was already loaded in $current_fruit or is this second time loaded from cache so its ok to load it again with that method?
    – Blissful
    Commented Sep 24, 2018 at 14:39
  • 1
    Yeah if you need to get a full list for other purposes, then filter that list into another array separately, you'll just need to use vanilla PHP functions. I don't know if that 2nd query would be cached, my instinct would say not
    – Clive
    Commented Sep 24, 2018 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.