php - 如何在 laravel 中获取嵌套数据
问题描述
逻辑
- 类别有产品
- 产品有
brand(1)
,options(0 or many)
,tags(0 or many)
,rating(0 or many)
- 我想在数组中的当前类别下获取每个
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.
解决方案
解决了
以下代码解决了我获取每个数据的数组的问题,但它仍然需要小的修复来返回我为此创建的新问题的唯一数据。
$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;
}
推荐阅读
- linq - 按特定顺序从另一个字符串中查找字符串数组中的所有字符串 mvc
- python - Kivy Python FileChooser()
- ios - PDFKit - 没有 usePageViewController() PdfView 不会是 RTL
- html - 我可以通过技巧将那些无序列表的圆圈与 html 对齐吗?
- javascript - Npm 本地依赖将生成一个新的 package-lock.json 与任何安装
- flutter - 如何在 Dart 中删除字符串开头和结尾的空格
- python - LSTM nlp 多类模型中的错误:- ValueError:形状(无,1)和(无,3)不兼容
- sql-server - 在 SQL Server 2017 中找不到“调试”菜单选项
- c# - 从python(jupyter notebook)运行c#函数
- scala - 见证抽象类型实现了类型类