在 null symfony 5 上调用成员函数 getId() 但存储库中的其他方法正在运行

Call to a member function getId() on null symfony 5 but other methods in respository are working

我正在尝试在我的 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 方法是错误的,尽管它正在运行,这里是堆栈跟踪的图像 enter image description here

因为 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()
        ];
       ...
    }