作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
品牌(1)
、选项(0 或多个)
、标签(0 或多个)
、评级( 0 个或多个)
brand
、options
、tags
、ratings
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/
我是一名优秀的程序员,十分优秀!