Aba*_*oub 7 php recursive-query laravel laravel-5.3
如何返回AllSubSections
(所有级别)的所有 ID
class Section extends Model
{
public function Ads()
{
return $this->hasMany(Ad::class);
}
public function AllSubSections()
{
return $this->SubSections()->with('AllSubSections');
}
public function SubSections()
{
return $this->hasMany(Section::class);
}
public function Parent()
{
return $this->belongsTo(Section::class);
}
}
Run Code Online (Sandbox Code Playgroud)
我目前正在做的是:
$section = Section::where('name', 'Properties')->first();
$subSections = $section->AllSubSections;
$subSections->pluck('id')
Run Code Online (Sandbox Code Playgroud)
但它只返回第一级而不是所有级别。
这是我带来的:
use Illuminate\Support\Collection;
class Section
{
public function children ()
{
return $this->hasMany(Section::class,);
}
public function parent ()
{
return $this->belongsTo(Section::class);
}
public function getAllChildren ()
{
$sections = new Collection();
foreach ($this->children as $section) {
$sections->push($section);
$sections = $sections->merge($section->getAllChildren());
}
return $sections;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,getAllChildren 是一个递归函数。它包含在子节上的循环,该循环将当前子项添加到集合中,并在此子项上再次调用自身。
然后您可以使用:
$section->getAllChildren()->pluck('id');
Run Code Online (Sandbox Code Playgroud)
你会得到你所有的孩子的身份证。
我希望我能回答这个问题!
归档时间: |
|
查看次数: |
2442 次 |
最近记录: |