Joomla Platform APIを使用して、サブクエリを含むクエリを実行する方法もあります。サブクエリの使用方法に関する基本的な考え方は、gunjanpatelに基づいています。
ネストされたセットモデルでクエリを実行する例を次に示します。
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>";