-1

资源集合:

public function toArray($request)
    {
        return [
            'test' => 55,
            'id' => $this->id,
            'name_en' => $this->name_en,
            'name_ar' => $this->name_ar,
            'slug' => $this->slug,
            'details' => $this->details,
            'currency' => $this->currency,
            'offer' => $this->offer->first(),
            'brand' => $this->brand,
            'category' => $this->category,
            'specifications' => SpesificationResource::collection($this->specifications),
            'merchant' => $this->merchant,
            'images' => count($this->images) > 0 ? ImageResource::collection($this->images) : asset("/images/default.png"),
            "price" => $this->price,
            "finalPrice" => $this->offer->first() ? $this->price - ($this->price * $this->offer->first()->discount / 100) : $this->price,
            'quantity' => $this->quantity,
            'inStock' => $this->inStock(),
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,

        ];
    }

控制器:

 public function show($id)
    {
        try {
            $product = new ProductResource(Product::findOrFail($id));
           return $product->test;
          //  return JsonResponse::respondSuccess(trans(JsonResponse::MSG_SUCCESS), $product);
        } catch (\Exception $e) {
            return JsonResponse::respondError($e->getMessage());
        }
    }

当我在控制器内使用测试值时,它不会返回,尽管当我从 Postman 调用它时它会返回。

这里有什么问题?

4

1 回答 1

0

$product是的一个实例,当然该类ProductResource没有属性。test而且它没有实现魔法__get方法。

所以你可以做的是要么使用$product['test']它实现的原因,ArrayAccess要么首先你可以做$product = (new ProductResource(Product::findOrFail($id)))->toArray($request);然后你可以再次使用$product['test']来获取test价值。

于 2021-08-06T08:21:51.770 回答