首页 > 解决方案 > 如何处理 laravel 资源中的嵌套关​​系 - 2

问题描述

所以我一直试图从我的“CategoryResource”中获得二级关系,但它不起作用,这是我的一些代码:

首先,我的模型:

public function children()
{
        return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function sub_children()
{
        return $this->hasMany(Category::class, 'parent_id');
}

然后是“CategoryResource”:

    $data = [

        'id' => $this->id,

        'parent_id' => $this->parent_id,
        'order' => $this->order,
        'name' => $this->name,
        'slug' => $this->slug,

        'childs' => CategoryResource::collection($this->whenLoaded('children') && $this->whenLoaded('children')),

        'created_at' => (string) $this->created_at,

        'updated_at' => (string) $this->updated_at,

    ];

我的控制器

    return CategoryResource::collection(Category::where('parent_id',null)->with('children.sub_children')->get());

无论如何我可以通过 laravel 资源检索我的嵌套关系吗?

标签: laravelapieloquent

解决方案


您可以with在关系中使用函数。它会是这样的:

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

它将加载孩子,然后加载“subChildren”作为第一个对象的关系。

因此,您将其加载为:

$children = $originalObject->children;
foreach ($children as $c) {
    $subChildren = $c->children;
}

检查这是否适用于您的问题。


推荐阅读