【问题标题】:Return object base on request uri根据请求 uri 返回对象
【发布时间】:2016-12-30 16:40:35
【问题描述】:

所以我有这个模块化的 web 应用程序,它具有与 zend 框架 1.12 集成的学说 2。

所以我想根据请求 uri 返回一个对象,例如:url/api/people/1,它根据他们的 id 返回一个人。

*旁注,我可以返回人的所有对象,我只想在用户输入数字后选择一个对象。

我尝试过的是从 url 中获取参数并将其传递给 find 函数,但是教义不理解这些通过 uri 传递的数字,并认为它们是动作。

  if($this->getRequest()->isGet())
  {
    $request = $this->getRequest();
    $id = $request->getParam('peopleId');

    $em = $this->getEntityManager();
    $peopleRepo = $em->getRepository('API\Entity\People');
    $people = $peopleRepo->find(3); //$id goes into find function

      $resultArray[] = 
      [
        'id'         => $people->getId(),
        'firstname'  => $people->getFirstName(),
        'lastname'   => $people->getLastName(),
        "food"       => $people->getFavoriteFood()
      ];
    echo json_encode($resultArray, JSON_PRETTY_PRINT);
    var_dump($people);

*****编辑***** 所以我添加了可以手动找到一个人的代码,但是我想通过 url 来做到这一点,我该如何实现呢?

【问题讨论】:

    标签: php zend-framework orm doctrine-orm uri


    【解决方案1】:

    试试:

    $peopleRepo = $em->getRepository('API\Entity\People')->findBy(array('id' => $id));
    

    或者

    $peopleRepo = $em->getRepository('API\Entity\People')->findById($id);
    

    参见 Doctrine 文档: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#by-simple-conditions

    【讨论】:

    • 您的两个建议都与问题相同。
    • @Cerad 我认为问题在于 Doctrine 找不到实体,但请求中的 $id 是正确的。 Paul Chu,您能给我们提供更多信息吗?
    • @hokusai 所以我编辑了帖子希望能回答你的问题。
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多