首页 > 解决方案 > 在 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 正在工作,这是堆栈跟踪的 图像在此处输入图像描述

标签: phpsymfonycontrollernulldoctrine

解决方案


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

推荐阅读