doctrine2 - symfony中使用Doctrine一对多映射在取对应Entity数组时的如何先排序?
给我你的怀抱
给我你的怀抱 2017-05-16 16:43:51
[PHP讨论组]

在使用Doctrine进行了一对多的映射,如一个人(Person),有多个小孩(Children),希望在使用Doctrine自动获取Children时,小孩能按年龄大小排序。

请问:要重载哪个函数才能实现呢?persion->getChildren()调用了哪个函数进行SQL查询呢?

这样的需求,很难搜索到结果,求前辈指点。

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

全部回复(2)
伊谢尔伦

解决方案如下:

修改Person类的getChildren方法

<?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);
    }
    
// ...

如果不想修改getChildren方法,可以写一个新的方法getChildrenOrderedByAge,道理同上。

总结:

Doctrine的一对多或者多对多关系中,Entity中所谓的属性是Doctrine\Common\Collections\Collection接口的某一实现的实例,默认情况下是Doctrine\Common\Collections\ArrayCollection,上述解决方案中用到的就是这一接口的Filtering API(筛选接口),上述情况下,筛选的条件会最终转化到SQL层进行处理,以达到性能优化的目的。

最后,相关官方文档链接如下:Filtering Collections

我想大声告诉你

使用 @vinzao 的方式没问题,不过 Doctirne 是提供了 OrderBy 方法的:

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;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号