还有一种方法可以使用 Joomla 平台 API 执行包含子查询的查询。如何使用子查询的基本思想是基于gunjanpatel。
这个答案也发布在Stackexchange for Joomla上。
这是在嵌套集模型上执行查询的示例:
SQL查询:
-- Find the Immediate Subordinates of a Node
SELECT node.title, (COUNT(parent.id) - (sub_tree.depth + 1)) AS depth
FROM lubd3_usergroups AS node,
lubd3_usergroups AS parent,
lubd3_usergroups AS sub_parent,
(
SELECT node.id, (COUNT(parent.id) - 1) AS depth
FROM lubd3_usergroups AS node,
lubd3_usergroups AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = 1
GROUP BY node.id
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.id = sub_tree.id
GROUP BY node.id
-- not showing the parent node
HAVING depth = 1
-- showing the parent node
-- HAVING depth <= 1
ORDER BY node.lft;
以及由 Joomla 执行的转换后的查询:
// Create the subQuery select statement.
// Nested Set Queries: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
// CROSS JOIN: http://www.informit.com/articles/article.aspx?p=30875&seqNum=5
$subQuery->select(array('node.id', '(COUNT(parent.id) - 1) AS depth'))
->from($db->quoteName('#__usergroups') . 'node')
->join('CROSS', $db->quoteName('#__usergroups', 'parent'))
->where($db->quoteName('node.lft') . ' BETWEEN ' . $db->quoteName('parent.lft') . ' AND ' . $db->quoteName('parent.rgt') . ' AND ' . $db->quoteName('node.id') . ' = ' . $db->quote('1'))
->group($db->quoteName('node.id'))
->order($db->quoteName('node.lft'));
// Create the base select statement.
$query->select(array('node.title', '(COUNT(parent.id) - (sub_tree.depth + 1)) AS depth'))
->from($db->quoteName('#__usergroups') . 'node')
->join('CROSS', $db->quoteName('#__usergroups', 'parent'))
->join('CROSS', $db->quoteName('#__usergroups', 'sub_parent'))
->join('CROSS', '(' . $subQuery .') AS sub_tree')
->where($db->quoteName('node.lft') . ' BETWEEN ' . $db->quoteName('parent.lft') . ' AND ' . $db->quoteName('parent.rgt')
. ' AND ' . $db->quoteName('node.lft') . ' BETWEEN ' . $db->quoteName('sub_parent.lft') . ' AND ' . $db->quoteName('sub_parent.rgt')
. ' AND ' . $db->quoteName('sub_parent.id') . ' = ' . $db->quoteName('sub_tree.id'))
->group($db->quoteName('node.id'))
->having($db->quoteName('depth') . ' = ' . $db->quote('1'))
->order($db->quoteName('node.lft'));
// Set the query and load the result.
$db->setQuery($query);
$rowList = $db->loadAssocList();
echo "<pre>";
print_r($rowList);
echo "</pre>";