Laravel资源集合显示空字段



我正在用Laravel开发一个API。在我正在访问的一个端点中,一些字段显示为空值,但它应该有一些信息。

注意"addicionais_descricao"one_answers";valor"字段,当我将它们包含在attributeitems数组中时,它们总是带空值,但如果我将其保留在初始级别,则会显示数据,但它不能解决我的情况,因为我需要属性项中的此信息:

输入图片描述

这是端点调用的地方,我在"Attribute"中进行查询表,该表与"attributeitem "表,而"属性项"表链接到"Attribute"one_answers"product".

public function show($id)
{
$atributos = Atributo::query('atributo')
->select(
'atributo.id',
'atributo.atrdescricao',
'atributoitens.atributo_id',
'atributoitens.produto_id',
'produto.prodescricao',
'produto.provalor'
)
->leftJoin('atributoitens', 'atributo.id', '=', 'atributoitens.atributo_id')
->leftJoin('produto', 'produto.id', '=', 'atributoitens.produto_id')
->where('atributo.id', '=', $id)
->get()->unique('id');
return AtributoResource::collection($atributos);
}

资源Atributo:

public function toArray($request)
{

return [            
'id' => $this->id,
'descricao' => $this->atrdescricao, 
'atributoitens' => AtributoitensResource::collection($this->atributoitens),
];
}

资源属性项:

public function toArray($request)
{        

return [
'id' => $this->id,
'atributo' => $this->atributo_id,
'produtos' => $this->produto_id,            
'adicionais_descricao' => $this->prodescricao,
'valor' => $this->provalor            

];
}

在这种情况下,正确的程序是什么?

以以下示例为参考:

控制器

$data = $shop->products()
->whereStatus(true)
->where('product_shop.active', true)
->where('product_shop.quantity', '>=', $this->min_product_qty)
->paginate(50);
return (new ProductCollection($data))
->response()
->setStatusCode(200);

ProductCollection

public function toArray($request)
{
return [
'data' => $this->collection
->map(function($product) use ($request) {
return (new ProductResource($product))->toArray($request);
}),
'brand' => $this->when($request->brand, $request->brand)
];
}

ProductResource

public function toArray($request)
{
return [
'type' => 'product',
'id' => (string) $this->id,
'attributes' => [
'uuid' => $this->uuid,
'name' => $this->name,
'slug' => $this->slug,
'description' => $this->description,
'thumb_path' => $this->thumb_path,
'cover_path' => $this->cover_path,
],
'relationships' => [
'brand' => $this->brand 
]
];
}

像这样的东西应该可以帮助您做您想做的事情。我不能为你做这件事。顺便问一下你为什么不用Eloquent之类的Attribute::where(...)->with(['relation_1', 'products'])->get();

public function toArray($request)
{
return [
'id' => $this->id,
'attributes' => [...],
'products' => $this->collection
->map(function($this->product) use ($request) {
return (new ProductResource($product))->toArray($request);
}),
];
}

相关内容

  • 没有找到相关文章

最新更新