我正在做一个项目Laravel。我有一个可以有父母或可以有孩子的帐户模型,所以我的模型设置如下:
public function immediateChildAccounts()
{
return $this->hasMany('Account', 'act_parent', 'act_id');
}
public function parentAccount()
{
return $this->belongsTo('Account', 'act_parent', 'act_id');
}
这很好用。我想做的是将所有孩子都放在某个帐户下。目前,我正在这样做:
public function allChildAccounts()
{
$childAccounts = $this->immediateChildAccounts;
if (empty($childAccounts))
return $childAccounts;
foreach ($childAccounts as $child)
{
$child->load('immediateChildAccounts');
$childAccounts = $childAccounts->merge($child->allChildAccounts());
}
return $childAccounts;
}
这也有效,但我不得不担心它是否很慢。这个项目是我们在工作中使用的旧项目的重写。我们将有数千个帐户迁移到这个新项目。对于我拥有的少数测试帐户,此方法不会造成性能问题。
有更好的解决方案吗?我应该只运行原始查询吗?做Laravel有什么办法可以处理这个吗?
总之对于任何给定帐户,我想要做的是在单个列表/集合中获取每个子帐户及其子帐户的每个子帐户等。一张图:
A -> B -> D
|--> C -> E
|--> F
G -> H
如果我运行 A->immediateChildAccounts(),我应该得到 {B, C}
如果我运行 A->allChildAccounts(),我应该得到 {B, D, C, E, F} (顺序无关紧要)
同样,我的方法有效,但似乎我做了太多查询。
另外,我不确定在这里问这个是否可以,但它是相关的。我怎样才能获得所有帐户的列表don't包括儿童账户吗?所以基本上与上面的方法相反。这样用户就不会尝试为帐户提供已经是子帐户的父帐户。使用上面的图表,我想要(以伪代码):
Account::where(account_id 不在 (A->allChildAccounts()) 中)。所以我会得到 {G, H}
感谢您的任何见解。