【问题标题】:How to handle nested relation in laravel resource - 2如何处理 laravel 资源中的嵌套关​​系 - 2
【发布时间】:2020-02-12 06:34:06
【问题描述】:

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

【问题讨论】:

    标签: laravel api eloquent


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 2023-04-08
      • 2019-01-16
      • 1970-01-01
      相关资源
      最近更新 更多