3

I am not a fan of writing long SQL queries and I am a huge fan of Views. When I need a list of nodes, for example for processing nodes in a cron task, I create a view and use views_get_view_result() to get the items and process them.

In Drupal 7, I think views_get_view_result() returned the node ID and other fields. In Drupal 8, it seems to be also including the fully loaded node object. Although this is very handy, as in most cases I am likely going to need the node object. Is this very memory efficient? Is passing hundreds or thousands of fully loaded node objects not going to cause memory issues?

Is there a way to only get node IDs and then let me use them to call Node::load()?

5
  • If you switch the View to display fields and add only the Node ID field you'll only get node IDs in the result. It's an opinion-based thing, but before I start to write lengthy queries I really like this method as well. drupal.stackexchange.com/a/295322/15055
    – leymannx
    Commented Feb 11, 2021 at 18:43
  • Thanks @leymannx. When my colleague had first set this up he was doing content format rather than fields; so I thought the reason. But I switched to fields and still passes full entities. I'll try the code you referenced in the morning.
    – liquidcms
    Commented Feb 12, 2021 at 6:02
  • 1
    Tried it again just to be sure and nope, using fields makes no difference; the full entities are passed regardless. Using the Views::getView() function is the same thing and also returns full entities. views_get_view_result() is just a wrapper for Views::getView()
    – liquidcms
    Commented Feb 12, 2021 at 6:32
  • You can always entity queries (I guess you already know that) But drupal wraps sql nicely, as far as entities go, and I think it is always the best solution for commands etc. Commented Feb 12, 2021 at 9:03
  • Ah interesting! I'd still consider that at least a loadMultiple have loaded the nodes then, so it's probably not much to worry about. But let's see if other answers are incoming.
    – leymannx
    Commented Feb 12, 2021 at 10:46

0

Your Answer

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

Browse other questions tagged or ask your own question.