简体   繁体   中英

Sorting embedded document in Symfony2 with Doctrine ODM

I'm unable to sort the embedded document. Here is my code.

Children.php

namespace Acme\CCBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class Children {
/..
    /**
     * @MongoDB\EmbedMany(targetDocument="Vaccine")
     */
    protected $vaccine = array();
}

Vaccine.php

namespace Acme\CCBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
 * @MongoDB\EmbeddedDocument
 */
class Vaccine
{
    /**
     * @MongoDB\Date
     */
    protected $recordDate;

    /**
     * @MongoDB\String
     */
    protected $vaccineName;
}

In my controller: RecordController.php

public function showVaccineAction($id) {
        $child = $this->get('doctrine_mongodb')
                ->getRepository('AcmeCCBundle:Children')
                ->find($id);

        $vac = $child->getVaccine();

        return $this->render(
                        'AcmeCCBundle:Record:show_vaccine.html.twig', array('vac' => $vac)
        );
    }

I just be able query all the vaccine of a child, and it's not ordered. Can anybody help me?

you can't sort embedded document in mongodb (respectively in doctrine odm).

you can use two option:

  1. update embedded document with sorting - you'll recreate documents, so no need to sorting(by default mongodb return documents sorted by created order). use this case if documents is not many and/or storing sorted result permanently

  2. use aggregation in mongodb -you'll denormalize by embedded document and sort by any way. big minus - the result may be difference from original document and can't hydrate to ODM class(problem with mapping to document). use this case if documents is too many and/or result stored temporary (eg only showing in template)

PS. no sorting command in your code ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM