【问题标题】:ArrayCollection in SymfonySymfony 中的 ArrayCollection
【发布时间】:2015-03-21 08:18:29
【问题描述】:

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

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

在文档中无法很好地理解...

提前致谢。

【问题讨论】:

    标签: symfony doctrine-orm arraycollection


    【解决方案1】:

    所以ArrayCollection 是一个简单的类,它实现了CountableIteratorAggregateArrayAccessSPL 接口,以及由 Benjamin Eberlei 制作的接口Selectable。 p>

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

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

    何时使用:

    • 通常用于对象关系映射,使用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 时配置模型时使用它。

    【讨论】:

    • 感谢您的回答!那么我怎样才能“使用”或“使用”这些集合呢?我已经/生成:实体在 __construct() 中添加了集合.. 但是为什么我需要这个?
    • ok 到目前为止这么好 thx ;-) 但我还有一个问题...如果我想列出所有订单(即 print_r($orders)),我的浏览器会被大量信息丢弃它崩溃了……这是由于关系吗? (一对多......外键等......)因为我认为没有关系就不会有这样的问题......
    • lazy-load 的概念出现了,实际上在对象$client 中不存在$orders,而是一个proxy 类,其中包含大量元数据,其中orders 是位于,它们是否在缓存中等等...这是教义的一个缺点,您不能 print_r 所有对象,通常您将遍历 ArrayCollection 中的每个对象并 Lazy-Load 进行显示。
    • $eman = $this->getDoctrine(); $company = $eman->getRepository('AppBundle:Company')->findOneBy(array('name'=>'test')); $users = $company->getUsers(); foreach ($users as $key) { echo $users['name']; } **抛出以下错误:不能使用 UserBundle\Entity\User 类型的对象作为数组 **....所以我又错了吗?
    • 如果您有时需要转储一些数据并且由于引用而陷入递归,请使用Doctrine的调试Doctrine\Common\Util\Debug::dump(),您还可以在其中指定深度。
    猜你喜欢
    • 2016-09-25
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多