Skip to content

Instantly share code, notes, and snippets.

@backbone87
Created November 8, 2017 16:29
Show Gist options
  • Save backbone87/70e5ad8aa9c61ba312778d79e32e35b7 to your computer and use it in GitHub Desktop.
Save backbone87/70e5ad8aa9c61ba312778d79e32e35b7 to your computer and use it in GitHub Desktop.
/**
* @return string
*/
protected function buildTreeNodeQuery() {
if($this->nodeQuery) {
return $this->nodeQuery;
}
$query = <<<EOT
SELECT
%s AS _key,
%s AS _parentKey,
descendants._hasChildren AS _hasChildren,
descendants._hasGrandChildren AS _hasGrandChildren,
(%s) AS _isSelectable,
%s
FROM
%s
AS tree
JOIN
(
SELECT
%s AS _key,
COUNT(child1._key) != 0 AS _hasChildren,
COUNT(grandchild1._key) != 0 AS _hasGrandChildren
FROM
%s
AS tree1
LEFT JOIN
(SELECT %s AS _key, %s AS _parentKey FROM %s %s)
AS child1
ON child1._parentKey = tree1.%s
LEFT JOIN
(SELECT %s AS _key, %s AS _parentKey FROM %s %s)
AS grandchild1
ON grandchild1._parentKey = child1._key
WHERE
%%s IN (%%s)
%s
GROUP BY
%s
%s
)
AS descendants
ON descendants._key = tree.%s
EOT;
$params = array();
// select
$params[] = $this->cfg->getKeyColumn();
$params[] = $this->cfg->getParentKeyColumn();
$params[] = $this->buildSelectableExpr();
$params[] = $this->buildNodeSelectExpr();
// from
$params[] = $this->cfg->getTable();
// select
$params[] = $this->cfg->getKeyColumn();
// from
$params[] = $this->cfg->getTable();
// child join
$params[] = $this->cfg->getKeyColumn();
$params[] = $this->cfg->getParentKeyColumn();
$params[] = $this->cfg->getTable();
$params[] = $this->cfg->getConditionExpr('WHERE');
$params[] = $this->cfg->getKeyColumn();
// grandchild join
$params[] = $this->cfg->getKeyColumn();
$params[] = $this->cfg->getParentKeyColumn();
$params[] = $this->cfg->getTable();
$params[] = $this->cfg->getConditionExpr('WHERE');
// where
$params[] = $this->cfg->getConditionExpr('AND');
// group by
$params[] = $this->cfg->getKeyColumn();
// having
$params[] = $this->cfg->getSelectionMode() == SQLAdjacencyTreeDataConfig::SELECTION_MODE_INNER
? 'HAVING _hasChildren'
: '';
// join
$params[] = $this->cfg->getKeyColumn();
$query = vsprintf($query, $params);
return $this->nodeQuery = $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment