问题
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