There is also a way to execute queries which contain subqueries using the Joomla Platform API.
The basic idea on how to use subqueries is based on gunjanpatel.
Here is an example for executing queries on Nested Set Models:
SQL query:
-- 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;
and the transformed query to be executed by 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>";
__toString()
) is a "magic" method.