【问题标题】:FOSRestBundle and Mongodb cursor object to jsonFOSRestBundle 和 Mongodb 游标对象到 json
【发布时间】:2012-12-11 09:54:48
【问题描述】:

我目前正在使用 Symfony2 和 FOSRestBundle 开发一个 RESTful API。

我喜欢 Mongodb,所以我已经实现了,这是我的用户控制器的 sn-p。

  /**
   * @return View view instance
   * @View()
   */
  public function allAction() {
    $users = $this->get('doctrine_mongodb')
      ->getRepository('FantasytdUserBundle:User')
      ->findByUsername('Elvar');

    return $users;
  }

所以我在数据库中找到了一个用户,这会产生一个结果。如果这是用 mysql 数据库完成的,那么这个 sn-p 就可以了。但是对于 mongodb,get 方法会返回一个 Cursor 对象,当返回 this 时,你会得到类似这样的东西。

[{"message":"[Semantical Error] Annotation @Secure is not allowed to be declared on class JMS\\SecurityExtraBundle\\Annotation\\Secure. You may only use this annotation on these code elements: METHOD.","class":"Doctrine\\Common\\Annotations\\AnnotationException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"\/Users\/Elvar\/Projects\/fantasytd\/backend\/vendor\/doctrine\/common\/lib\/Doctrine\/Common\/Annotations\/AnnotationException.php","line":52,"args":[]},

它还在继续。

我应该如何处理这些光标对象?

【问题讨论】:

  • 如果你尝试使用 Secure(roles="ROLE_ADMIN") 注释来保护整个控制器,你得到的错误会在 Symfony 2.1 中抛出。请改用@PreAuthorize("hasRole('ROLE_ADMIN')")(请参阅:stackoverflow.com/a/12001097/601386)。
  • 如果您使用@PreAuthorize,请不要忘记将expressions: true 添加到jms_security_extra: 下的配置中。默认为false

标签: php mongodb rest symfony


【解决方案1】:

我们没有使用 foreach 循环遍历列表,而是在 Cursor 对象上使用“->toArray()”——它只是更简单一点。 我相信 iterator_to_array() 也可以解决问题。

【讨论】:

    【解决方案2】:

    如果结果只产生一个结果,显然它可以工作,因此使用 FindOneByUsername() 可以解决问题。

    如果您需要多个结果,我通过循环解决了它。

     public function allAction() {
        $usersQ = $this->get('doctrine_mongodb')
          ->getRepository('FantasytdUserBundle:User')
          ->findByUsername('Elvar');
    
        foreach ($usersQ as $user) {
          $users[] = $user;
        }
    
        return $users;
      }
    

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多