Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify a default order for a Doctrine 2 model?

In Rails (and even in Doctrine < 2, IIRC) you can specify a default order for any model. For example, if you tell Rails to always order your customer table by name, Customer.all will always a list of customers ordered by name. It makes an enormous amount of sense.

From what I gather it's not possible to do this in Doctrine 2. Evidently they want you to create a query instead.

It would be a very DRY, logical and convenient feature to include, and an outstandingly stupid feature to choose to leave out, it seems to me.

I sincerely hope I'm wrong about this option not existing, and before I cry myself to sleep tonight, I wanted to check to see if maybe Doctrine does actually have a way to specify a default order and I just haven't been able to find it. Can anyone enlighten me?

like image 359
Jason Swett Avatar asked Sep 05 '25 09:09

Jason Swett


1 Answers

Whilst you don't seem to be able to do this for an entire model ala Doctrine 1, you can specify ordering as a notation on the inverse side of a relation:

// Entity/Category

/**
 * @var ArrayCollection $posts
 *
 * @ORM\OneToMany(targetEntity="Post", mappedBy="category")
 * @ORM\OrderBy({"name" = "ASC"})
 */
private $posts;

Also, if you're implementing entity manager services such as those in SonataNewsBundle, you can specify defaults via optional arguments i.e.

class PostManager extends ModelPostManager
{

    /**
     * {@inheritDoc}
     */
    public function findBy(array $criteria, array $orderBy = array('name' => 'asc'))
    {
        return $this->em->getRepository($this->class)->findBy($criteria, $orderBy);
    }
}
like image 74
Steve Avatar answered Sep 08 '25 18:09

Steve