Symfony2 and Ordering of Relations and Collection Form Fields
Recently I was working on a project where I kept finding myself ordering a relation over and over by other than something than ID order (ie id= 1,2,3,4,5). For example, I always wanted my relation to be ordered by the ‘name’ field, rather than the ID or order it was inserted into the DB. Let’s take this schema as an example:
CREATE TABLE IF NOT EXISTS `post` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(32) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `post_attachment` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(32) NULL ,
`url` VARCHAR(32) NULL ,
`post_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_post_attachment_post_idx` (`post_id` ASC) ,
CONSTRAINT `fk_post_attachment_post`
FOREIGN KEY (`post_id` )
REFERENCES `post` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
The issue is each time I attempted:
<?php
$attachments = $post->getPostAttachments();
foreach($attachments as $attachment)
{
echo $attachment->getId().' '.$attachment->getName()."\n";
}
//Output
// 1 d name
// 2 c name
// 3 a name
// 4 b name
I wanted the output to be in alphabetical order for example. To make this the default for that relation you can add the following annotation to your ‘Post’ entity:
<?php
//MyBundle/Entity/Post.php
...
class Post
{
...
/**
* @ORM\OneToMany(targetEntity=PostAttachment",mappedBy="post")
* @ORM\OrderBy({"name"="ASC"})
*/
private $post_attachments;
...
}
Now if you do “$post->getPostAttachments()” they’ll be automatically in order. The ‘@ORM\OrderBy’ column takes care of the ordering automatically. You can specify as many columns on the relation as you’d like there. In addition, this will make it so that all form collections on post with post_attachments are also ordered by name, rather than ID. This affects the relation call every time. If you are only looking into having it some of the time, look into using the repository to do the ordering for those calls.





