drupal 8商业获取产品返回空对象

时间:2020-03-13 09:48:27

标签: php drupal drupal-commerce

所以我创建了一些产品并向其中添加了一些数据:

enter image description here

然后在我的自定义路线中,我尝试使用以下代码将所有产品淘汰:

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

但是这将返回以下响应:

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

有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

JSON响应未编码超过第一深度。据我所知,使用new JsonResponse()时您无法控制。

一种解决方案是构建自己的数据结构并手动编码JSON。此解决方案使用序列化程序服务:https://drupal.stackexchange.com/a/191474/70331

在您的情况下,类似这样的代码应该对完整的实体结构进行编码。

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;

如果使用“序列化器”,则最好通过依赖注入将其提供给控制器。

相关问题