在null symfony 5上调用成员函数getId(),但repository中的其他方法正在工作



我正在尝试在我的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方法是错误的allhard正在工作,这是堆栈跟踪的图像在此处输入图像描述

因为vehicle/list在vehicle/{id}函数之后。它正在获取id作为"列表">

您可以将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()
];
...
}

相关内容

最新更新