Home > Software engineering >  Doctrine only select last entry of collection
Doctrine only select last entry of collection

Time:11-14

I have the following Entity :

class Product
{
     /**
     * @ORM\OneToMany(targetEntity="App\Entity\StockEntry", mappedBy="product")
     *
     * @Groups({"product:read", "product:read:all"})
     */
    private Collection $stockEntries;

    public function getStockEntries(): Collection
    {
        return $this->stockEntries;
    }

    public function getLastBuyPrice(): float
    {
        /** @var StockEntry $lastEntry */
        $lastEntry =  $this->getStockEntries()->last();
        if ($lastEntry) {
            return $lastEntry->getBuyPrice() ?: 0.;
        }
        return 0.;
    }
}

My problem is that when I call my getLastBuyPrice() method, All StockEntries are retrieved, which can be very long (a product can have hundreds of stock entries). I'm looking for a way to rewrite getLastBuyPrice() so that only the most recent StockEntry is retrieved to compute the lastBuyPrice.

CodePudding user response:

I recommend that you create a method in "StockEntryRepository". This method will retrieve the last item you need without iterating through all of the items.

  • Related