在 Laravel 中选择递归模型关联中的特定字段

问题描述 投票:0回答:0

我有一个“程序”表来存储具有许多字段的程序,包括“名称”字段或属性。该表具有“parent_id”字段,因此该表可以存储嵌套的程序层次结构。这是“孩子”关系的

Program.php
模型定义:

public function children()
{
    return $this->hasMany(Program::class, 'parent_id')->with(['children']);
}

一切正常,直到我必须执行自定义查询来限制字段数量,即仅“id”和“name”字段对为某些嵌套下拉/复选框字段生成 JSON 对象。 (这个表有100+个字段)

为此,我想使用“选择”查询方法进行查询。这是代码:

$query = $query->with([
    'children' => function ($query) use ($notIn) {
        $subquery = $query->select('id', 'name', 'parent_id');
        return $subquery;
    }
]);

虽然上面的代码只适用于一个级别。查看示例输出:

[
    {
        "id": 1,
        "name": "Program 1",
        "children": [
            {
                "id": 3,
                "name": "Program 3",
                "parent_id": 1,
                "children": []
            },
            {
                "id": 11,
                "name": "New program here copy",
                "parent_id": 1,
                "children": [
                    {
                        "id": 2,
                        "parent_id": 11,
                        "name": "Program 2",
                        "type": "default",
                        "budget_summary": null,
                        (...includes all fields)
                        "children": [
                            {
                                "id": 12,
                                "parent_id": 11,
                                "name": "Program 2",
                                "type": "default",
                                "budget_summary": null
                                (...includes all fields)
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

如何限制比第一层更深的层中的字段数?我已经尝试了那里建议的很多东西,但还没有奏效。

laravel select nested children has-many
© www.soinside.com 2019 - 2024. All rights reserved.