9

I was wondering if there is a way to declare the default order for my doctrine models.

e.g.

I have a work model and it has photos. When I load a work, all photos associated to it get loaded into $work->photos. When I display them, they are ordered by their IDs.

It would be very convenient to declare a default order on another field or perhaps override the fetch behaviour altoghether.

I'd rather not to convert the photos to an array and use usort. Thanks.

Arend
  • 3,741
  • 2
  • 27
  • 37
Ignacio
  • 7,947
  • 15
  • 63
  • 74

3 Answers3

10

You can specify it in the YAML as follows:

If it's a sorting order for a field in the table itself add:

options:
  orderBy: fieldname

where options: is at the same depth as you'd have a columns: or relations: entry. NB: The capitalisation of orderBy: is vital; get it wrong and you'll get no error but also no sorting.

If it's a sorting order for a relationship then, within the relationship you can skip the options: part and just put in:

orderBy: fieldname
borrible
  • 17,120
  • 7
  • 53
  • 75
  • 4
    Or by @OrderBy annotation: http://www.doctrine-project.org/docs/orm/2.0/en/reference/annotations-reference.html#annref-orderby – Alex Nov 21 '11 at 12:49
  • Which yml file are you doing this in? – Squazic Aug 15 '12 at 20:01
  • It depends. In doctrine1, the answer is valid (and it is about schema YAML file), but in doctrine2 it is just impossible to do. As a workaround, see @Alex's comment. – Frizi Dec 01 '12 at 14:54
  • 1
    @OrderBy annotation is only applicable to relationships. It doesn't work on top-level entities. "You may only use this annotation on these code elements: PROPERTY" Also, this answer doesn't provide any way to define order direction. – Hayden May 09 '17 at 20:00
4

OK, I got around this thanks to this post: http://www.littlehart.net/atthekeyboard/2010/02/04/sorting-relationship-results-in-doctrine-1-2-2/

In my case, the BaseWork.php file had this modifications:

public function setUp()
    {
        parent::setUp();
        $this->hasMany('Photo as photos', array(
             'local' => 'id',
             'orderBy' => 'display_order',
             'foreign' => 'work_id'));

Anyhow, it would be better to specify this in schema.yml, which I couldn't make work.

Ignacio
  • 7,947
  • 15
  • 63
  • 74
0

I don't know the first thing about doctrine, but it looks like you can specify an order by clause when you call create().

http://www.doctrine-project.org/documentation/manual/1_0/en/dql-doctrine-query-language:order-by-clause

Brian L
  • 10,757
  • 5
  • 19
  • 17