如何有效地加载ArrayCollection中的最后一项? [英] How to efficiently load last item in ArrayCollection?

查看:55
本文介绍了如何有效地加载ArrayCollection中的最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2个实体:

public class Domain {
    ...
    /**
    * @ORM\OneToMany(targetEntity="Application\Entity\Ping", mappedBy="domain", cascade={"persist", "remove"}, fetch="EXTRA_LAZY")
    * @ORM\OrderBy({"time" = "ASC"})
    */
    private $pings;
    ...
}

和:

class Ping{
    ...
    /**
     * @ORM\ManyToOne(targetEntity="Application\Entity\Domain", inversedBy="pings")
     * @ORM\JoinColumn(name="proj_id", referencedColumnName="proj_id")
    */
    private $domain;
    ...
 }

我目前在我的表中有数百个域名,每个域名都有5K-8K Pings.

I have currently a couple of hundred domains with 5K-8K Pings each in my tables.

在域概述(每页限制为50个域)中,我想显示所有ping的计数以及最后一次ping的结果.在显示收藏夹数量的过程中,没有任何问题,我无法有效地获取收藏夹的最后一个元素.

In an overview of the domains - limited to 50 domains per page - I want to display the count of all pings and the result of the last ping. While displaying the count of the collection works without any issues I can't fetch the last element of the collection efficiently.

我尝试使用

$domain->getPings()->last();

$domain->getPings()->get( $key );

在两种情况下,结果都是相同的:

In both cases the result is the same:

允许使用的内存大小为134217728字节...

Allowed memory size of 134217728 bytes exhausted ...

如何有效地进行最后一次ping?

How can i get the last ping efficiently?

推荐答案

要在实体中有效过滤集合而不需要存储库,可以使用

To filter your collection efficiently in the entity without the need for the repository you can use a Criteria. It will allow to filter a collection that's been already loaded into memory or do it directly in sql if not. Quoting from the documentation:

如果尚未从数据库中加载集合,则过滤API可以在SQL级别上工作,以优化对大量收藏

If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections

只需将以下方法添加到您的 Domain 实体.

Just add the following method to your Domain Entity.

use Doctrine\Common\Collections\Criteria;

// ...

/**
 * Get last ping for the domain.
 * @returns Ping
 */
public function getLastPing()
{
    $c = Criteria::create();
    $c->setMaxResults(1);
    $c->orderBy(['time' => Criteria::DESC]);
    $this->pings->matching($c)->first();
}

这篇关于如何有效地加载ArrayCollection中的最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆