我试图使用Laravel的资源集合来转换所有产品的json数据。但这是在抛出错误。
“此集合实例上不存在属性名称”。
我检查了官方文档,他们也以类似的方式实现了它。
ProductController.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
];
}
}ProductResource.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);
}发布于 2018-10-21 09:14:44
ProductCollection用于Products的集合。
所以你需要用外汇。
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;
}
}发布于 2019-11-29 06:38:22
通过使用“集合”静态方法,您可以使用资源返回集合,而无需循环:
public function index()
{
return ProductCollection::collection(Product::all());
}发布于 2019-11-06 04:04:43
我所发现的是,如果你想要的话,你永远不必循环这个集合。
在我的例子中,我有一个事件集合。我所做的就是这个。
php artisan make:resource Event
php artisan make:resource EventCollection
在事件中
return [
"id" => $this->id,
"title" => $this->title,
"parent_id" => $this->parent_id,
"color" => $this->color,
"start" => $this->start_date,
"end" => $this->end_date
];在EventCollection中,让它保持原样:
return parent::toArray($request);https://stackoverflow.com/questions/52913385
复制相似问题