douhuan6305 2015-06-17 11:09
浏览 11
已采纳

Symfony中对象的order属性

I would like to reorder the attribute (COMMENTS) of my object (instance of ARTICLE) after I retrieve it from the DBB. Is this possible?

My object is ARTICLE and it is linked to COMMENTS (which is defined as a collection in entity article)

I know I can order through the repository but the order of my comments depend on many conditions, some not available through the DB.

Condition exemple: I want at the top the comment whose attribute show_first are set to true whatever their score, and then the other comments ordered depending of their score.

  • 写回答

2条回答 默认 最新

  • dongzhenshen7435 2015-06-17 13:03
    关注

    You could add a hidden field to you query that sorting things in the order that you wanted so that you don't need to process the complete ArrayCollection to sort.

    public function findByArticleInOrderOfState()
    {
        return $this->createQueryBuilder('c')
            ->select('c')
            ->addSelect('
                CASE 
                    WHEN c.state = :state_new THEN 1
                    WHEN c.state = :state_viewed THEN 2
                    WHEN c.state = :state_deleted THEN 3
                    ELSE 4
                END AS HIDDEN order_by
            ')
            ->setParameter('state_new', 'new')
            ->setParameter('state_viewed', 'viewed')
            ->setParameter('state_deleted', 'deleted')
            ->orderBy('order_by', 'ASC')
            ->addOrderBy('c.createdAt', 'ASC')
            ->getQuery()
            ->getResults();
    }
    

    This would create a hidden field order_by and set that depending on the current state of that object, then it would order by that hidden field and then createdAt.

    It doesn't really make sense to order comments like that but it does show how you could do it. With a little more info on the actual use case I would (hopefully) be able to make work a bit closer to your specific needs.

    Update

    In your case when you have show_first == 'yes'|'no' you could do the following..

    public function findByArticleInOrderOfState()
    {
        return $this->createQueryBuilder('c')
            ->select('c')
            ->addSelect('
                CASE 
                    WHEN c.show_first = :show_first THEN 1
                    ELSE 2
                END AS HIDDEN order_by
            ')
            ->setParameter('show_first', 'yes')
            ->orderBy('order_by', 'ASC')
            ->addOrderBy('c.createdAt', 'ASC')
            ->getQuery()
            ->getResults();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用