Cross posted on the “Metal Toad Blog”:http://metaltoad.com/blog/recursively-load-nodes-rich-data-model
If you’ve ever worked with a rich data model in drupal you know it can be a pain
to load up all the children and parents of a node within the templating engine.
One method that could save you a lot of time is to load the data recursively
in node_load and save your poor front-end guy some wrist pain (or yourself if you’re
Edit: Please look at the get_metadata() definition towards the bottom or none of this is going to make sense.
Here is the initial bit which loads on details about a node. Here of course you
could load all manner of things like read/write attributes, cck fields, etc.
One thing we found was that search would break when trying to index since it was
trying to load all the data from associated nodes as well. One way of dealing with
this is to use hook_nodeapi(‘update index’) to only load a subset of data instead
of the whole shebang. But I didn’t do it like that and I’m not going to put untested
code on the blog (well, aside from slightly edited code).
This is what I did instead. It’s interesting for its hackishness. There must be a
better way though.
Here we get to the fun part though. This bit loads up the parents, those that this
node belongs to. Due to performance constraints when doing this you need to pick
a direction to load infinitely. If you choose to load parents recursively you have
easier code and it’s actually a lot faster as far as SQL is concerned. If you choose
to load children recursively, as I will do in a moment, the SQL is a little slower
but on-the-fly SQL is easier to write for a belongs_to relationship. When all the
data necessary is already in the db row you load to build yourself it’s easy to
include your parents too.
So you’ll note that here we load up a collection of parents being careful to make
sure that the recursive function knows who called it by the parent attribute on $obj.
Very similarly, here we load up the children. This time we load recursively with
no end condition. This is prone to cycles so you may have to go with a non-recursive
loader here if you have a cyclic loading cycle or some other way of terminating
Here’s where we load extra attributes from the node addon table that you see associated
with every custom content-type. These attributes just get added onto the node directly
so there is some concern about columns named with php reserved words. Conflicting
column names like title just need to be carefully considered, they may not actually
be bad a bad idea.
This is just a sample of our metadata loader. Naturally you could do this some other
way but it works pretty well for us. There is room for improvement though, using
a different format like YAML could buy some extra win for instance.