递归地在Yii中找到嵌套的活动记录关系

时间:2014-03-01 22:01:38

标签: php activerecord recursion yii cactiverecord

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

- 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;等等。)

你会怎么做?

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

这是gist of my solution(链接中的代码注释):

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

1 个答案:

答案 0 :(得分:0)

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

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

我在Yii中使用此扩展程序也会保留预先排序的内容,这很不错http://www.yiiframework.com/extension/nestedsetbehavior/