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



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

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

您有没有想过使用预购来一次性获得所有细节?如果可能的话,把账户和客户都放在一个表中,那么一个带有预购的查询实际上会得到你需要的一切。

如果你把客户和账户放在两个不同的表中,我相信你仍然可以使用预购来最大限度地减少查询次数。

我在Yii中使用了这个扩展程序,也可以保持预订,这很好http://www.yiiframework.com/extension/nestedsetbehavior/

最新更新