0

So I currently have multiple different product types that have varying fields. I was able to fetch all products using EntityTypeManager the following way:

$productStorage = \Drupal::entityTypeManager()->getStorage('commerce_product');
$ids = $productStorage->getQuery()->execute();
$allProducts = $productStorage->loadMultiple($ids);

This works quite well, and I see how this can be used to execute more complicated queries. However, I'd like to now get a certain product (perhaps based off the product_id). I saw a previous post showing that a dynamic query is faster than an EntityFieldQuery. So if for example my custom api call (my drupal is communicating with a frontend server) gets a request for a certain product by product_id and product type, how can I determine the fields of the product type with which I can then create a dynamic database query to get the product and the field values that go along with it? I read somewhere that this information is stored in the config table in the database and shouldn't really be queried, which is why I'm asking this question.

Thanks for the help in advance, and let me know if there's anything unclear about my post!

2
  • \Drupal::entityTypeManager()->getStorage('commerce_product')->load($id) I guess I don't understand the question.
    – leymannx
    Nov 17 at 22:32
  • 1
    I'm not clear on what you are asking either.
    – Jaypan
    Nov 17 at 22:34

1 Answer 1

1

how can I determine the fields of the product type with which I can then create a dynamic database query to get the product and the field values that go along with it?

You shouldn't do that. That's what the entity API already does. You would just be rebuilding the existing functionality of core Drupal for no benefit. Then there's contrib modules, which extend and augment that functionality. You would need to reproduce everything relevant that they do as well.

This sounds like a classic case of premature optimisation, which rarely has the intended benefits in my experience. Drupal has a great caching system, it would be advisable to look into that as a way to mitigate issues, if and when they actually present as real world problems.

As an aside, as a literal answer to the original question, this is how you get the fields of an entity bundle:

$field_defs = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('commerce_product', 'bundle');

$fields_names = array_keys($field_defs);
1
  • Ok I see. I thought there's a significant difference in execution time between the entity API and database query, and it's more worth it to use database queries directly. Thanks for clearing it up... I'll stick to the entity API then. Nov 19 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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