Roman
Roman

Reputation: 2549

How to retrieve only one row for Doctrine2 entity?

I am working with the entities Price and Product. Every Product has several Prices. With the getter Product->getPrices i can retrieve all Prices. Every Price has a field insertedAt which stores a DateTime object.

My Problem

I want to retrieve only the latest Price for a Product but i dont know how to do this.

Solution (by Maerlyn)

https://stackoverflow.com/a/24715756/2139671

(UPDATE) My next problem

I am using not only then insertedAt-field but also a condition and a source-field. So i need to retrieve the current price for every condition and source. Do you have a solution for that problem, too?

Upvotes: 0

Views: 63

Answers (1)

Maerlyn
Maerlyn

Reputation: 34107

You can use the OrderBy annotation to define which order the related entities are returned; use it like this:

/**
 * @ORM\OneToMany(targetEntity="Price")
 * @ORM\OrderBy({"insertedAt" = "DESC"})
 */
private $prices;

Then add a method to retrieve the current price:

public function getCurrentPrice()
{
    return $this->prices->first();
}

Upvotes: 2

Related Questions