简体   繁体   English

drupal 8 commerce获取产品返回空对象

[英]drupal 8 commerce get product returns empty object

So i have created a few products and added some data to it:所以我创建了一些产品并添加了一些数据:

在此处输入图片说明

In my custom route i am then trying to get all products out using the following code:在我的自定义路线中,我尝试使用以下代码获取所有产品:

$products = \Drupal\commerce_product\Entity\Product::loadMultiple();
$response['data'] = $products;
$response['method'] = 'GET';
return new JsonResponse($response);

However this returns the following reponse:但是,这会返回以下响应:

{"data":{"3":{},"6":{},"7":{}},"method":"GET"}

Can anyone tell me what ive done wrong?谁能告诉我我做错了什么?

The JSON response is not encoding past the first level of depth. JSON 响应未编码超过第一级深度。 As far as I can tell, you cannot control that when using new JsonResponse() .据我所知,在使用new JsonResponse()时您无法控制它。

One solution is to build your own data structure and encode the JSON manually.一种解决方案是构建您自己的数据结构并手动编码 JSON。 This solution uses the serializer service: https://drupal.stackexchange.com/a/191474/70331此解决方案使用序列化程序服务: https : //drupal.stackexchange.com/a/191474/70331

In your case, something like this should encode the full entity structure.在你的情况下,像这样的东西应该对完整的实体结构进行编码。

use Drupal\commerce_product\Entity\Product;
use Symfony\Component\HttpFoundation\JsonResponse;
...

$products = Product::loadMultiple([$ids]);

$response['data'] = $products;
$response['method'] = 'GET';

$serializer = \Drupal::service('serializer');
$jsonResponse = JsonResponse::fromJsonString($serializer->serialize($response, 'json'));
return $jsonResponse;

If using the 'serializer' it is best to provide that to the controller via dependency injection.如果使用“序列化器”,最好通过依赖注入将其提供给控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM