php - Laravel:此集合实例上不存在属性 [名称]
问题描述
我正在尝试使用 Laravel 的资源集合转换所有产品的 json 数据。但它正在抛出错误。
“此集合实例上不存在属性 [名称]”。
我检查了官方文档,他们以类似的方式实现了它。
产品控制器.php
public function index()
{
return new ProductCollection(Product::all());
}
ProductCollection.php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ProductCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'price' => $this->price
];
}
}
产品资源.php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'description' => $this->detail,
'price' => $this->price,
'stock' => $this->stock,
'discount' => $this->discount,
'effectivePrice' => round($this->price * (1 - ($this->discount/100)), 2),
'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star') / $this->reviews->count(), 2) : 'No Ratigs Yet',
'href' => [
'reviews' => route('reviews.index', $this->id)
]
];
}
}
注意:不转换 ProductCollection 时工作正常,即 ProductCollection 的toArray()函数如下所示:
public function toArray($request)
{
return parent::toArray($request);
}
解决方案
ProductCollection
用于集合Products
。
所以你需要使用foreach。
class ProductCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
// final array to be return.
$products = [];
foreach($this->collection as $product) {
array_push($products, [
'name' => $product->name,
'price' => $product->price
]);
}
return $products;
}
}
推荐阅读
- delphi - 使用画布绘制二次函数图
- mysql - 包含所有两个表信息的第三个表
- javascript - Angular 如何将 2 个数据传递给子组件并使用 ngOnChanges 和 SimpleChanges
- sql - 问:如何获取一个案例的结果以在另一个操作中使用它?| SQL
- sql - 根据 id 列评估两个表中的 int 列,更新其总和
- python - 如何使用 sudo apt-get 在 Linux 上将 python 模块安装到特定的 python 版本
- string - 文本文件中的 Perl 字符串比较
- c# - 如何使用 microsoft bot 框架在瀑布模型中实现下拉列表
- ruby-on-rails - 将 content_for 与脚本标签的 src 属性一起使用?
- python - 格式字符串错误的参数过多(** 中的代码)