【问题标题】:Symfony2 's mongoDB returns a loggablecursor instead of my entitiesSymfony2 的 mongoDB 返回一个 loggablecursor 而不是我的实体
【发布时间】:2012-04-15 01:31:48
【问题描述】:

我目前使用 DoctrineMongoDbBundle 向我的 mongodb 数据库发出请求。

这是我的控制器中的调用:

    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1")); 

    echo print_r($entities->getQuery());
    echo printf(count($entities));
    echo get_class($entities);

然后我尝试将 $enitities 序列化为 json 并将其发送给客户端,但没有成功。

打印的回声:

Array ( [prop] => 1 ) 
101
Doctrine\ODM\MongoDB\LoggableCursor0

表示查询正确,但计数应为“2”,类型应为Animal数组。

为什么存储库返回 LoggableCursor0 而不是 Animal 数组?

[编辑] 它怎么会返回一个 Animal 数组?

[edit] 以 JSON 格式返回结果的最佳方式是什么?

【问题讨论】:

    标签: php mongodb symfony


    【解决方案1】:

    findBy returns MongoDB ODM 中的 Cursor 与学说 orm 不同。

    试试:

    echo printf($entities->count());
    

    【讨论】:

    • 有没有办法像 ORM 一样获取实体?怎么样?
    • @Anton:+1,这是我的问题
    • @AntonBabenko 没办法。虽然 Cursor 是可迭代的,并且您可以构建自己的实体数组,但在大多数情况下您不需要照顾它。
    • 谢谢您的回答。在 json 中返回 the.result 的最佳方法是什么?
    • @Jean-PhilippeLeclerc 假设您正在制作 API,最好的方法是使用支持 json/xml 的 JMSSerializerBundle,配置应序列化的属性并以适当的方式序列化日期时间.
    【解决方案2】:

    使用方法toArray()。像这样:

    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"))->toArray(); 
    

    如果您需要获取实体数组,请使用array_values() 函数。像这样:

    $entities = array_values($entities);
    

    【讨论】:

    • 原因是我在那个项目中使用了 ORM 并且通过实体循环。现在我将项目迁移到 ODM 并且不想处理重写视图:)
    • 但是你可以查看Cursor,不是吗?
    • 可以,但为此我必须重写视图。
    • 也许我什么都不知道,但 {% foreach item in items %} where items is Cursor 应该与传递 ->toArray() 的结果相同?
    • 你是对的,在大多数情况下它工作正常,但当代码使用索引在视图中显示某些项目时就不行了。像这样 - {{images.0.title}}、{{images.3.title}}、{{images.5.title}}。如果我使用 Cursor,那么我必须使用 toArray() 并使用 array_values() 创建一个数组以使用索引。
    【解决方案3】:

    如果您在将实体存储为数组时想要更多的灵活性,您可以这样做

    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $animalLoggableCursors = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"));
    
    $animals = array()
    while ($animal = $animalLoggableCursors->getNext()) {
        if ($animal->getSomeProperty() == $someValue)
            array_push($animals, $animal)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 2016-01-21
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多