我如何 select 我的递归 child 调用中的某些列

How can I select certain columns from my recursive child call

我是 Eloquent 的新手,我在思考一些问题时遇到了问题。

基本上我有一个 table,我从同一个 table 中递归地抓取 children。

public function children() {
    return $this->hasMany(static::class, 'parent_org_id');
}

public function childrenRec()
{
    return $this->children()->with('childrenRec');
}

其中childrenRec是基于'parent_org_id'

对所有children的递归调用

我在静态函数中从下面调用它,截至目前我只想要 idname_en org

self::select('id','name_en')->where('parent_org_id','=',0)->with('childrenRec')->get()->toArray();

正在获取顶级组织(我的顶级 orgparent_org_id 为 0)。

我的问题是,在递归抓取的 children 中,它不限于 idname_en

我的问题归结为: 我如何才能 select 我的递归 child 调用中的某些列,以及这是 'proper' 做事的方式?

我返回的数组如下所示。

array:1 [▼
  0 => array:4 [▼
    "id" => 1
    "name_en" => "Org Unit"
    "org_type" => null
    "children_rec" => array:2 [▼
      0 => array:27 [▼
        "id" => 2
        "name_en" => "My First Orgunit."
        "code" => null
        "abbreviation" => null
        "address1" => "222 Street Street"
        "address2" => null
        "city_id" => 1
        "province_id" => 14
        "postalcode" => "C161L7"
        "country_id" => 38
        "contact_name" => null
        "contact_title" => null
        "email" => "test@test.com"
        "fax" => "902-555-5555"
        "phone1" => "5125125125125"
        "phone2" => null
        "org_type_id" => 1
        "parent_org_id" => 1
        "ref_id" => 79
        "has_users" => 1
        "created_at" => "2016-11-02 18:47:55"
        "updated_at" => "2016-11-02 18:47:55"
        "org_type" => array:4 [▶]
        "children_rec" => array:1 [▶]
      ]
      1 => array:27 [▶]
    ]
  ]
]

提前致谢。

要在 with() 方法中访问关系查询,您可以使用一个以关系名称作为键的数组和一个注入 QueryBuilder 实例的闭包。

一个 'gotcha' 在执行此操作时花了我很长时间才找到解决方案的是,您的 parent 和 children 查询需要包含关联它们关系的键,因为模型 attached/associated 彼此 两个查询分别 运行 之后。这些模型使用模型关系中定义的列相互关联。如果您的查询中没有模型关联中使用的列,则不会附加相关模型。在您的情况下,它将是:

self::select('id','name_en')
    ->where('parent_org_id','=',0)
    ->with(['childrenRec' => function($query) {
        return $query->select('id', 'name_en', 'parent_org_id');
    }])
    ->get()
    ->toArray();

如果您不在子查询中包含 parent_org_id,则不会附加关系。

Docs

试试这个:

public function childrenRec()
{
    return $this->children()->with(['childrenRec' => function($query){               
         $query->select('id','name_en');
    }]);
}