【发布时间】:2015-03-21 08:18:29
【问题描述】:
因为我对 Symfony 和 Doctrine 还很陌生,所以我遇到了一个可能很愚蠢的问题 ;-)
有人可以用简单的话向我解释集合(尤其是实体中的 ArrayCollections)吗?它是什么以及何时以及如何使用它们? (也许是一个简单的例子)
在文档中无法很好地理解...
提前致谢。
【问题讨论】:
标签: symfony doctrine-orm arraycollection
因为我对 Symfony 和 Doctrine 还很陌生,所以我遇到了一个可能很愚蠢的问题 ;-)
有人可以用简单的话向我解释集合(尤其是实体中的 ArrayCollections)吗?它是什么以及何时以及如何使用它们? (也许是一个简单的例子)
在文档中无法很好地理解...
提前致谢。
【问题讨论】:
标签: symfony doctrine-orm arraycollection
所以ArrayCollection 是一个简单的类,它实现了Countable、IteratorAggregate、ArrayAccessSPL 接口,以及由 Benjamin Eberlei 制作的接口Selectable。 p>
如果您不熟悉SPL 接口,这里的信息不多,但ArrayCollection - 允许您以类似数组的形式但以OOP 方式保存对象实例。使用ArrayCollection 而不是标准的array 的好处是,当您需要像count、set、unset 这样的简单方法迭代到某个特定值时,这将为您节省大量时间和工作量对象,最重要的是非常重要:
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 时配置模型时使用它。
【讨论】:
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 类型的对象作为数组 **....所以我又错了吗?