php - 在 null symfony 5 上调用成员函数 getId() 但存储库中的其他方法正在工作
问题描述
我正在尝试在我的 symfony 应用程序中使用 findAll 方法,该方法 findOneBy 工作正常,它看起来像这样:
/**
* @Route("vehicle/{id}", name="findById", methods={"GET"})
*/
public function findById($id): JsonResponse {
$vehicle = $this->vehicleRepository->findOneBy(['id' => $id]);
$data = [
'id' => $vehicle->getId(),
'VIN' => $vehicle->getVIN()
];
return new JsonResponse($data, Response::HTTP_OK);
}
但是 find all 方法不起作用,它看起来像这样:
/**
* @Route("vehicle/list", name="listAll", methods={"GET"})
*/
public function findAll(): JsonResponse {
$vehicles = $this->vehicleRepository->findAll();
$data = [];
foreach ($vehicles as $vehicle) {
$data[] = [
'id' => $vehicle->getId(),
'VIN' => $vehicle->getVIN()
];
}
return new JsonResponse($data, Response::HTTP_OK);
}
我得到的错误如下,由于某种原因告诉我方法 findById 是错误的,alltough 正在工作,这是堆栈跟踪的 图像在此处输入图像描述
解决方案
因为vehicle/list 在vehicle/{id} 函数之后。它的 id 作为“列表”</p>
您可以将 listAll 函数放在 findById 之前,或者您可以使用优先级注释。
这是
/**
* @Route("vehicle/list", name="listAll", methods={"GET"})
*/
public function findAll(): JsonResponse {
$vehicles = $this->vehicleRepository->findAll();
$data = [];
foreach ($vehicles as $vehicle) {
$data[] = [
'id' => $vehicle->getId(),
'VIN' => $vehicle->getVIN()
];
}
return new JsonResponse($data, Response::HTTP_OK);
}
/**
* @Route("vehicle/{id}", name="findById", methods={"GET"})
*/
public function findById($id): JsonResponse {
$vehicle = $this->vehicleRepository->findOneBy(['id' => $id]);
$data = [
'id' => $vehicle->getId(),
'VIN' => $vehicle->getVIN()
];
return new JsonResponse($data, Response::HTTP_OK);
}
此外,如果您在 findById 函数上使用类型提示,如果 id 不存在,您将能够获得 404。
例如
/**
* @Route("vehicle/{vehicle}", name="findById", methods={"GET"})
* @param Vehicle $vehicle
*/
public function findById(Vehicle $vehicle): JsonResponse {
$data = [
'id' => $vehicle->getId(),
'VIN' => $vehicle->getVIN()
];
...
}
推荐阅读
- android - 当 apk 已在 Playstore 中上传时,Firebase ID 始终返回 null
- javascript - 对js数字表示和他的位操作有疑问?
- java - java spark - 为什么是我的数据集
错误?
- html - react CSS是在className中定义的,没有任何外部css文件,它是如何工作的?
- java - 一对一映射 Hibernate
- python - 如何在pygame中添加再次播放按钮
- angular - 当使用角度在amcharts4中找不到数据时如何显示“未找到记录”消息
- postgresql - 在这个简单的 postgresql 示例中,"SELECT 1 + 1" :: IO [Only Int] 如何成为 Query 类型?
- reactjs - React Native:如何在特定屏幕中禁用抽屉?
- javascript - 如何在刷新时将文件存储在我的 chrome 扩展中?