Laravel返回所有后代的ID [英] Laravel return all the ids of descendants

查看:105
本文介绍了Laravel返回所有后代的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回 AllSubSections (所有级别)的所有ID

How do I return all the ids of AllSubSections (all levels)

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

当前正在做的事情:

$section = Section::where('name', 'Properties')->first();
$subSections = $section->AllSubSections;
$subSections->pluck('id')

但它仅返回第一个级别,而不是所有级别.

but it only returns the 1st level not all the levels.

推荐答案

这是我自带的:

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

如您所见,getAllChildren是一个递归函数.它在子级部分上包含一个循环,该循环将当前子级添加到集合中,并在此子级上再次调用自身.

As you can see, getAllChildren is a recursive function. It contains a loop over the section children that adds to the collection the current child and calls itself again on this child.

然后您可以使用:

$section->getAllChildren()->pluck('id');

您将获得所有孩子的身份证.

And you will get all your children ids.

我希望我能回答这个问题!

I hope I am responding to the question!

这篇关于Laravel返回所有后代的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆