symfony - Symfony 中的数组集合

标签 symfony doctrine-orm arraycollection

因为我对 Symfony 和 Doctrine 还很陌生,所以我有一个可能很愚蠢的问题;-)

有人可以用简单的词语向我解释集合(尤其是实体中的ArrayCollections)吗?它是什么以及何时以及如何使用它们? (也许在一个简单的例子中)

在文档中无法很好地弄清楚......

提前致谢。

最佳答案

所以ArrayCollection是一个实现 Countable 的简单类, IteratorAggregate , ArrayAccess SPL接口(interface),以及接口(interface) SelectableBenjamin Eberlei制作。

如果您不熟悉SPL,那么这里的信息并不多。接口(interface),但是 ArrayCollection - 允许您以类似数组的形式但以 OOP 方式保存对象实例。使用 ArrayCollection 的好处,而不是标准array当您需要像 count 这样的简单方法时,这将为您节省大量时间和工作。 , set , unset迭代到某个对象,最重要的是非常重要:

  • Symfony2 使用 ArrayCollection在他的核心中,如果你配置得当的话,它会为你做很多事情:
    • 将为您的关系生成“一对一、多对一……等”的映射
    • 将在您创建嵌入表单时为您绑定(bind)数据

何时使用它:

  • 通常用于对象关系映射,当使用doctrine时,建议只添加annotations为您的属性,然后在命令 doctrine:generate:entity 之后setter 和 getter 将被创建,对于像 one-to-many|many-to-many 这样的关系在构造函数类中将被实例化ArrayCollection类而不仅仅是一个简单的 array

    public function __construct()
    {
        $this->orders = new ArrayCollection();
    }
    
  • 使用示例:

    public function indexAction()
    {
        $em = $this->getDoctrine();
        $client = $em->getRepository('AcmeCustomerBundle:Customer')
                     ->find($this->getUser());
    
        // When you will need to lazy load all the orders for your 
        // customer that is an one-to-many relationship in the database 
        // you use it:
        $orders = $client->getOrders(); //getOrders is an ArrayCollection
    }
    

    实际上您并没有直接使用它,而是在设置 setter 和 getter 时配置模型时使用它。

关于symfony - Symfony 中的数组集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29180651/

相关文章:

translation - 如何在 Twig 中进行复数翻译?

php - 类别树的路由

symfony - @param注解在symfony2类文件中有什么作用

apache-flex - 弹性 : Swapping two elements in Array Collection

mongodb - ArrayCollection 中的命名集合键

交响乐 2.8 : inject mocked repository in a test controller

configuration - Symfony2 : updating just one vendor bundle

symfony - SonataDoctrineORMAdminBundle 抛出 array_combine 错误

php - Doctrine 2 - 如何在 where 子句中使用鉴别器列

symfony - 在 where 条件下的学说 ORM 计数数组集合