0

假设您有如下关系,并且您想要查找给定客户下的所有帐户:

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

(对于客户 1,它是帐户 1、2、3、4 和 5;对于客户 3,它是帐户 4 和 5;以此类推)

你会怎么做?

这在我的项目中出现过几次,我很好奇其他人是如何解决它的。

是我的解决方案的要点(链接中的代码注释):

<?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;
}
4

1 回答 1

0

您是否考虑过使用预购来一次性获取所有详细信息?如果可能的话,将帐户和客户都保存在 1 个表中,然后 1 个预购查询实际上会得到您需要的一切。

如果您将客户和帐户保存在 2 个不同的表中,我相信您仍然可以使用预购来最大限度地减少您执行的查询次数。

我在 Yii 中使用这个扩展也可以保持预购,这非常好http://www.yiiframework.com/extension/nestedsetbehavior/

于 2014-03-02T00:16:05.010 回答