2012-12-25 19 views
0

我目前正在使用Symfony2和FOSRestBundle一起使用RESTful API。FOSRestBundle和Mongodb游标对象json

我喜欢Mongodb,所以我实现了这一点,这里是我的usercontroller的一个片段。

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

    return $users; 
    } 

所以我在数据库中找到一个用户,这会产生一个结果。这是用MySQL数据库完成这段代码将工作。但是对于mongodb,get方法返回一个Cursor对象,当它返回时,你会得到类似的东西。

[{"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":[]}, 

然后继续。

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

+0

如果您尝试使用'Secure(roles =“ROLE_ADMIN”)'注释来确保整个控制器的安全,则会在Symfony 2.1中引发错误。使用'@PreAuthorize(“hasRole('ROLE_ADMIN')”)'代替(参见:http://stackoverflow.com/a/12001097/601386)。 – flu

+0

如果您使用@PreAuthorize,请不要忘记在'jms_security_extra:'下为您的配置添加'expressions:true'。它默认为'false'。 – flu

回答

2

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

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

public function allAction() { 
    $usersQ = $this->get('doctrine_mongodb') 
     ->getRepository('FantasytdUserBundle:User') 
     ->findByUsername('Elvar'); 

    foreach ($usersQ as $user) { 
     $users[] = $user; 
    } 

    return $users; 
    } 
1

而是通过与foreach循环列表中运行,我们正在使用的“ - >指定者()”光标对象 - 它只是一个简单一点。 我相信iterator_to_array()也应该这样做。