I admit; I am not a fan of writing length SQL queries and I am a huge fan of Views. Many times when I need a list of nodes (such as processing nodes in a cron task), I have created a View and then used views_get_view_result to get my items (and process them).

In D7 I think views_get_view_result returned the NID and whatever other fields I had added to my View. In D8, 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 and this means I do not need to load it in my code; but, 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 pass NIDs and then let me loop through them and do a Node::load()?

  • 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 Feb 11 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 Feb 12 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 Feb 12 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. – M.Anagnostopoulos Feb 12 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 Feb 12 at 10:46

Your Answer

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

Browse other questions tagged or ask your own question.