如何在Laravel中获取嵌套数据

时间:2020-07-17 03:51:40

标签: php laravel

逻辑

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

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

代码

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.

2 个答案:

答案 0 :(得分:1)

已解决

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

    $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;
    }

答案 1 :(得分:0)

与您使用急切加载来检索与该类别相关的产品的方式相同,您还可以使用nested eager loading来加载那些产品关系。

引用文档:

要急于加载嵌套关系,可以使用“点”语法。例如,让我们急切地在一项雄辩的陈述中加载本书的所有作者和作者的所有个人联系人:

对于您的特定查询,您可以执行以下操作:

$category = Category::where('active', 'yes')
    ->where('slug', $slug)
    ->with(
        'products.brand', 
        'products.options', 
        'products.tags', 
        'products.ratings'
    )->first();

然后,您可以像查询返回的任何对象一样访问数据:

@foreach($category->products as $product
    <h1>{{ $product->brand->title }}</h1>
    @foreach($product->tags as $tag)
        <span>{{ $tag->title }}</span>
    @endforeach
@endforeach
相关问题