Question

Suppose you have a relation like the following, and you want to find all accounts that are under a given customer:

- Customer 1
    - accounts
        - Account 1
    - customers
        - Customer 2
            - accounts
                - Account 2
                - Account 3
        - Customer 3
            - customers
                - Customer 4
                    - accounts
                        - Account 4
                        - Account 5

(For Customer 1, it's accounts 1, 2, 3, 4, and 5; for Customer 3, it's accounts 4 and 5; etc.)

How would you do that?

This has come up a few times in my projects and I'm curious how others have solved it.

Here's the gist of my solution (code comments in link):

<?php
public function getNestedRelated($nested, $from, $nestedCriteria = array(), $fromCriteria = array(), $maxLevels = false, $includeFirst = true, $_currentLevel = 0, &$_recursedSoFar = array())
{
    // Always return an array (for array_merge)
    $related = array();

    // Prevent infinite recursion
    if (in_array($this->primaryKey, $_recursedSoFar)) {
        return $related;
    }
    $_recursedSoFar[] = $this->primaryKey;

    // Nested records at this level
    if ($_currentLevel > 0 || $includeFirst) {
        // Whether to refresh nested records at this level. If criteria are
        // provided, the db is queried anyway.
        $refreshNested = false;
        $related       = $this->getRelated($nested, $refreshNested, $nestedCriteria);
    }

    // Handle singular ("HAS_ONE", "BELONGS_TO") relations
    if (!is_array($related)) {
        $related = array($related);
    }

    // Don't recurse past the max # of levels
    if ($maxLevels !== false && $_currentLevel > $maxLevels) {
        return $related;
    }

    // Whether to refresh children of this record. If criteria are provided,
    // the db is queried anyway.
    $refreshFrom = false;

    // Go down one more level
    $_currentLevel++;
    foreach ($this->getRelated($from, $refreshFrom, $fromCriteria) as $child) {
        // Recursive step
        $nestedRelated = $child->getNestedRelated($nested, $from, $nestedCriteria, $fromCriteria, $maxLevels, $includeFirst, $_currentLevel, $_recursedSoFar);
        $related       = array_merge($related, $nestedRelated);
    }
    return $related;
}

No correct solution

OTHER TIPS

Have you thought about using preorder to get all the details in 1 go? If it is possible, keep both accounts and customers in 1 table, then 1 query with preorder would actually get everything you need.

If you keep the customers and accounts in 2 different tables, I believe you could still use preorder to minimize the number of queries you do.

I use in Yii this extension too keep things in preorder, it is quite nice http://www.yiiframework.com/extension/nestedsetbehavior/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top