How to efficiently load last item in ArrayCollection?

泪湿孤枕 提交于 2021-01-29 08:00:18

问题


I have the following 2 entities:

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

and:

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

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

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.

I tried to get the element with

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

and

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

In both cases the result is the same:

Allowed memory size of 134217728 bytes exhausted ...

How can i get the last ping efficiently?


回答1:


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:

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

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();
}


来源:https://stackoverflow.com/questions/57670661/how-to-efficiently-load-last-item-in-arraycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!