gpt4 book ai didi

php - 如何在laravel中获取嵌套数据

转载 作者:行者123 更新时间:2023-12-04 04:01:43 25 4
gpt4 key购买 nike

逻辑

  1. 类别有产品
  2. 产品有品牌(1)选项(0 或多个)标签(0 或多个)评级( 0 个或多个)
  3. 我想获取数组中当前类别下的所有brandoptionstagsratings

Note: returned data are category based not database based, so each category return different set of data based on what has been provided to that category products.

代码

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

类别模型

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

产品型号

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.

最佳答案

已解决

以下代码解决了我获取每个数据数组的问题,但它仍然需要一些小的修复才能返回我创建的唯一数据 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;
}

关于php - 如何在laravel中获取嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62946817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com