如何在Laravel资源中处理嵌套关系-2

时间:2019-10-15 14:30:28

标签: laravel api eloquent

所以我一直在尝试从我的“ 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资源检索我的嵌套关系吗?

1 个答案:

答案 0 :(得分:0)

您可以在关系中使用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;
}

检查是否可以解决您的问题。