开发者

Querying drupal nodes based on multiple term/node references

I need to query drupal nodes based on a taxonomy term which is several reference hops away from the content type I need to query.

I'm given a term id for a term which contains a term_reference. The referenced term contains a node reference. The referenced nodes are what I'm trying to get. Is there a clean开发者_运维技巧 way to do this?


Yes, there are clean ways to do this, but I can't give very specific advice without actually seeing your data structure. I would start at the beginning and just var_dump() at every step.

For example, first fetch the term corresponding to the term ID you're given:

$term = taxonomy_term_load($tid);
var_dump($term);

Look at the var_dump() to see how to access your term reference field. I'm guessing it will be something like this:

foreach (field_get_items('taxonomy_term', $term, 'YOUR_TERM_REFERENCE_FIELD') as $referenced_term) {
    var_dump($referenced_term);
}

Then see what you are given in there. Then, after that, do the same to fetch all of the referenced nodes.

The whole process will basically involve looping through each level, loading the references, looping through those, loading the references, and so on until you have the nodes you need. So you may end up with something like the following, assuming your term reference field is called field_term_reference and your node reference one is field_node_reference:

$nodes = array();
$term = taxonomy_term_load($tid);
foreach (field_get_items('taxonomy_term', $term, 'field_term_reference') as $referenced_tid) {
    $referenced_term = taxonomy_term_load($referenced_tid['tid']);
    foreach (field_get_items('taxonomy_term', $referenced_term, 'field_node_reference') as $referenced_nid) {
        $nodes[] = node_load($referenced_nid['nid']);
    }
}

return $nodes;

Also, for what it's worth, after you finally are able to retrieve your nodes, you may want to go back through your code and combine some of the foreach loops into the D7 functions that load multiple entities, like taxonomy_term_load_multiple() and node_load_multiple(). This will reduce calls to the database and make things a bit more performant.

If you'd like a more specific answer, feel free to post more details about your data and I'll update my answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜