首页 > 解决方案 > 如何在 laravel 中获取嵌套数据

问题描述

逻辑

  1. 类别有产品
  2. 产品有brand(1), options(0 or many), tags(0 or many),rating(0 or many)
  3. 我想在数组中的当前类别下获取每个brand, options, tags,ratings

注意:返回的数据是基于类别而不是基于数据库的,因此每个类别根据提供给该类别产品的内容返回不同的数据集。

代码

Controller

public function show($slug)
{
    $category = Category::where('active', 'yes')->where('slug', $slug)->with('products')->first();
    return response()->json([
        'data' => new CategoriesFrontResource($category),
        'success'=>'Category retrieved successfully'
    ], 200);
}

Category model

public function products(){
  return $this->belongsToMany(Product::class, 'category_products', 'category_id', 'product_id');
}

Product model

public function categories(){
  return $this->belongsToMany(Category::class, 'category_products', 'product_id', 'category_id');
}

public function options(){
  return $this->belongsToMany(Option::class, 'option_products', 'product_id', 'option_id');
}

public function tags(){
  return $this->belongsToMany(Tag::class, 'product_tags', 'product_id', 'tag_id');
}

public function brand(){
  return $this->belongsTo(Brand::class);
}

public function rating(){
  return $this->morphMany(Rating::class, 'rateable');
}

知道如何实现这一目标吗?

更新

根据Jeemusu这里的回答是我目前所拥有的

$category = Category::where('active', 'yes')->where('slug', $slug)->with(['products', 'products.options', 'products.variations', 'products.brand', 'products.tags', 'products.rating'])->first();
$products = $category->products;
$tags = $products->tags->toArray();

这就是结果

Property [tags] does not exist on this collection instance.

标签: phplaravel

解决方案


解决了

以下代码解决了我获取每个数据的数组的问题,但它仍然需要小的修复来返回我为此创建的新问题的唯一数据。

    $data = [];
    foreach($products as $i => $product) {
        $data[$i]['brand'] = $product->brand;
        $data[$i]['rating'] = $product->rating;
        $data[$i]['variations'] = $product->variations;
        $data[$i]['options'] = $product->options;
        $data[$i]['tags'] = $product->tags;
    }

推荐阅读