doctrine2 - How to sort the corresponding Entity array when using Doctrine one-to-many mapping in symfony?
给我你的怀抱
给我你的怀抱 2017-05-16 16:43:51
0
2
688

I am using Doctrine for one-to-many mapping, such as a person (Person) and multiple children (Children). I hope that when using Doctrine to automatically obtain Children, the children can be sorted by age.

Excuse me: Which function should be overloaded to achieve this? persion->Which function does getChildren() call to perform SQL query?

It is difficult to find results for such a demand, so please give me some advice.

给我你的怀抱
给我你的怀抱

reply all(2)
伊谢尔伦

The solution is as follows:

ModificationPerson类的getChildrenMethod

<?php
// src/AppBundle/Entity/Person.php
// ...

use Doctrine\Common\Collections\Criteria;

//...

    /**
     * @param string $orderedByAge "ASC"|"DESC"
     */
    public function getChildren($orderedByAge=null)
    {
        if (null === $orderedByAge) {
            return $this->children;
        }
        
        if (!in_array(strtoupper($orderedByAge), ['ASC', 'DESC'])) {
            throw new \InvalidArgumentException('参数错误,必须是"ASC"或"DESC"中的一个');
        }
        
        $order = 'ASC' === $orderedByAge ? Criteria::ASC : Criteria::DESC;
        
        $criteria = Criteria::create()->orderBy(['age' => $order]);
        
        return $this->children->matching($criteria);
    }
    
// ...

If you don’t want to modify itgetChildren方法,可以写一个新的方法getChildrenOrderedByAge, the same principle applies.

Summary:

Doctrine的一对多或者多对多关系中,Entity中所谓的属性是DoctrineCommonCollectionsCollection接口的某一实现的实例,默认情况下是DoctrineCommonCollectionsArrayCollection,上述解决方案中用到的就是这一接口的Filtering API(筛选接口),上述情况下,筛选的条件会最终转化到SQL layer processing to achieve performance optimization.

Finally, the relevant official document link is as follows: Filtering Collections

我想大声告诉你

It’s okay to use @vinzao’s method, but Doctirne provides the OrderBy method:

Person:

<?php

// src/AppBundle/Entity/Person.php

class Person
{
    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Children", mappedBy="person")
     * @ORM\OrderBy({"age"="DESC"})
     */
    protected $childrens;
}

Children:

<?php

// src/AppBundle/Entity/Children.php

class Children
{
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Person", inversedBy="childrens")
     */
    protected $person;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template