Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php drupal 8 commerce get产品返回空对象_Php_Drupal_Drupal Commerce - Fatal编程技术网

Php drupal 8 commerce get产品返回空对象

Php drupal 8 commerce get产品返回空对象,php,drupal,drupal-commerce,Php,Drupal,Drupal Commerce,因此,我创建了一些产品并添加了一些数据: 在我的定制路线中,我尝试使用以下代码取出所有产品: $products = \Drupal\commerce_product\Entity\Product::loadMultiple(); $response['data'] = $products; $response['method'] = 'GET'; return new JsonResponse($response); 但是,这将返回以下响应: {"data":{"3":{},"6":{},

因此,我创建了一些产品并添加了一些数据:

在我的定制路线中,我尝试使用以下代码取出所有产品:

$products = \Drupal\commerce_product\Entity\Product::loadMultiple();
$response['data'] = $products;
$response['method'] = 'GET';
return new JsonResponse($response);
但是,这将返回以下响应:

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

谁能告诉我我做错了什么吗?

JSON响应的编码深度没有超过第一级。据我所知,在使用
newjsonresponse()
时,您无法控制这一点

一种解决方案是构建自己的数据结构并手动编码JSON。此解决方案使用序列化程序服务:

在您的例子中,类似这样的东西应该编码完整的实体结构

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;
如果使用“序列化器”,最好通过依赖项注入将其提供给控制器