Rob Forrest
Rob Forrest

Reputation: 7450

doctrine ordering toMany associations by entity

I'm looking to order a OneToMany association in an entity with the slight caveat that the specific property I'd like to order by isn't within that entity but a property of something that it is associated with.

Sorry for the confusing start, lets attempt to clarify the situation with an example. I'd like to be able to do something akin to:

class download
{
    /**
     * @ORM\OneToMany(targetEntity="entity\download\file", mappedBy="download", indexBy="id")
     * @ORM\JoinColumn(name="download_id", referencedColumnName="download_id")
     * @ORM\OrderBy({"mime_type.extension" = "ASC"})
     */
    protected $files = null;
}

Where a download has many files and each file has one mime_type

Currently I end up with ORMException: Unrecognized field: mime_type

Is this possible or am I simply asking for too much?

Upvotes: 6

Views: 2670

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32392

http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-orderby

The DQL Snippet in OrderBy is only allowed to consist of unqualified, unquoted field names and of an optional ASC/DESC positional statement. Multiple Fields are separated by a comma (,). The referenced field names have to exist on the targetEntity class of the @ManyToMany or @OneToMany annotation.

In your case extension does not exist on the targeted entity (which is file). Instead, it exists on the entity mime_type, so it's one level too deep. I don't think it's possible to use @OrderBy to order by a field multiple levels deep.

You might consider moving the extension field (or really all mime_type fields) into file. And using

 * @ORM\OrderBy({"extension" = "ASC"})

Upvotes: 6

Alessandro Lai
Alessandro Lai

Reputation: 2274

An other solution, useful if you can't change your DB structure: you could apply the OrderBy clause inside a repository, writing a full DQL query where you join all the 3 tables:

SELECT d
FROM download AS d
LEFT JOIN files AS f
LEFT JOIN mime_type AS m
ORDER BY m.extension

Upvotes: 4

Related Questions