2

I would like to use a example query for retrieving a full tree of the nested set model in a dynamic query.

SELECT node.name
FROM nested_category AS node,
        nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;

The problem is that dynamic queries can't alias the same table. Is there a work around for this?

4
  • the question is whether a dynamic query would be a good fit for the situation, most probably a static query would be enough ? Even the official doc is surprisingly discouraging regarding to dynamic queries ...
    – mojzis
    Commented Mar 3, 2013 at 21:41
  • and BTW: i love the nested set idea :) i havent seen it used in drupal yet ... is this some public stuff ?
    – mojzis
    Commented Mar 3, 2013 at 21:44
  • The nested set modal also know as the modified preorder tree traversal algorithm has a good explanation found on Sitepoint. It has some benefits over the adjacent tree model which is used in Drupal Taxonomy for maintaining term hierarchies because it can pull a tree with a single query while the adjacent tree model requires less resources to update. See the Drupal leftandright module and the Drupal lineage module
    – Adam S
    Commented Mar 4, 2013 at 1:53
  • @mojzis why would a static query be enough ? If he wants other modules to be able to alter this query such as changing the value passed to parent.name ... or add other Joins ... then that's what dynamic queries are for. Dynamic queries are easier to build APIs with, or allow flexability in a library.
    – tenken
    Commented Mar 4, 2013 at 4:15

1 Answer 1

0

The best answer I have at this point is to simply execute the subquery first using fetchAssoc() to return an array.

$subquery = db_select('nested_category', 'parent');
$subquery->addField('parent', 'lft');
$subquery->addField('parent', 'rgt');
$subquery->condition('name', $name, '=');
$parent = $subquery->execute()->fetchAssoc();

$query = db_select('nested_category', 'node');
$query->addField('node', 'name');
$query->condition('node.lft',$parent, 'BETWEEN');
$results = $query->execute()->fetchAll();

Your Answer

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

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