如何避免使用内存,或清除内存,当从ArrayCollection中检索第一个项目


How do I avoid using memory, or clear memory, when retrieving only the first item from an ArrayCollection?

/**
* @OneToMany(targetEntity="DocumentData", mappedBy="document")
**/
private $records;

我目前有上述。我使用下面的命令来检索第一条记录。

function getFirstRecord() {
  if (isset($this->records[0])) {
    return $this->records[0]->getData();
  }
  else {
    return FALSE;
  }
}

它使用了太多的内存(循环遍历100个文档后使用了3MB到128MB)。我想这是因为在这一行:

if (isset($this->records[0])) {

整个$records ArrayCollection被加载到内存中,但我只需要$records[0]。一旦我有了第一个记录,我该如何避免这种情况或将其从记忆中清除?

编辑:

我现在有:

  /**
  * @OneToMany(targetEntity="DocumentData", mappedBy="document", fetch="EXTRA_LAZY")
  **/
  private $records;

  function getFirstRecord() {
    $header;
    if ($this->records->containsKey(0)) {
      $header = $this->records->get(0);
      return $header->getData();
    }
    else {
      return FALSE;
    }
  }

不幸的是,get和containsKey方法仍然加载整个ArrayCollection。有人能看出我做错了什么吗?

我的最终解决方案是使用原始SQL查询。

SELECT column FROM documentdata WHERE document_id = ". $docid ." LIMIT 1

我不需要特定的记录,任何记录都可以。我无法从fetch="EXTRA_LAZY"中获得预期的输出