php - Laravel 返回后代的所有 ID

标签 php laravel laravel-5.3 recursive-query

如何返回 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);
    }
}

目前正在做的是:

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

但它只返回第一个级别而不是所有级别。

最佳答案

这是我带来的:

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 是一个递归函数。它包含一个遍历 children 部分的循环,该循环将当前子项添加到集合中并再次调用该子项。

然后你可以使用:

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

您将获得所有 child 的 ID。

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

关于php - Laravel 返回后代的所有 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414434/

相关文章:

mysql - Laravel:MySQL 每天自动更新我的 Updated_at 字段,但文章没有任何更新

php - 通知 : Undefined variable: _SESSION in "" on line 9

javascript - 选择单选按钮后的下拉列表

php - alias 可以在 $row 中工作吗?

php - 拉拉维尔 5.2 : set and get session with multiple variables

laravel - 获取具有多个 id 的单个查询中的所有行

php - 如何在 magento 中以编程方式将产品及其自定义选项信息保存到另一个表

Laravel Homestead 每个项目安装 Bash 别名命令未找到

javascript - 如何调整图像的方向以显示正确的图像预览?

javascript - 在 v-for 循环中使用 vue 组件