【发布时间】:2021-09-07 15:32:13
【问题描述】:
我有一个marketer 表,每个营销人员可能有多个营销人员,也可能属于一个营销人员。我已经编写了这个方法来检查我是否可以获得一个特定营销人员的多个级别:
表:
id parent_id name
1 NULL a
2 1 b
3 2 c
4 1 d
5 3 e
6 2 f
7 4 g
营销者模型:
public function parent()
{
return $this->belongsTo(Self::class);
}
public function children()
{
return $this->hasMany(Self::class,'parent_id');
}
方法:
public function marketerWithSubs(Marketer $marketer, $index = 1, $output = [])
{
$output = [];
foreach ($marketer->children as $firstLevel){
$output[1][] = $firstLevel->id . '- ' . $firstLevel->full_name;
foreach ($firstLevel->children as $secondLevel){
$output[2][] = $secondLevel->id . '- ' . $secondLevel->full_name;
foreach ($secondLevel->children as $thirdLevel) {
$output[3][] = $thirdLevel->id . '- ' . $thirdLevel->full_name;
foreach ($thirdLevel->children as $forthLevel) {
$output[4][] = $forthLevel->id . '- ' . $forthLevel->full_name;
foreach ($forthLevel->children as $fifthLevel) {
$output[5][] = $fifthLevel->id . '- ' . $fifthLevel->full_name;
foreach ($firstLevel->children as $sixthLevel) {
$output[6][] = $sixthLevel->id . '- ' . $sixthLevel->full_name;
}
}
}
}
}
}
return $output;
}
方法示例输出,这是我所期望的,数组中的索引,显示(所谓的)submarketer 的级别,值是 submarketers ids 作为数组:
array:6 [▼
1 => array:27 [▶]
2 => array:23 [▶]
3 => array:32 [▶]
4 => array:8 [▶]
5 => array:5 [▼
0 => 102
1 => 63
2 => 64
3 => 65
4 => 67
]
6 => array:35 [▶]
]
如何将其转化为实用的方法?
【问题讨论】:
-
你能不能表现出关系以及期待。所以很容易想到。谢谢