假设您有如下关系,并且您想要查找给定客户下的所有帐户:
- 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;
}