简体   繁体   English

祖先:按孩子人数排序

[英]Ancestry: sorting on number of children

I want to sort my parent object on basis of number of children it has. 我想根据其具有的子代数对父对象进行排序。 Ancestory has this method 'child_ids' which return all the children ids. Ancestory具有此方法“ child_ids”,该方法返回所有子代id。 Is there a way I can use that to sort my parent objects? 有什么办法可以对父对象进行排序吗?

 Project.order(child_ids.count)

or 要么

 Project.order(Project.child_ids.count)

don't work. 不工作 I guess that is obvious. 我想这很明显。 Any other way to sort on basis of children can work too. 以儿童为基础进行排序的任何其他方法也可以使用。 Thanks! 谢谢!

EDIT: look at ancestry column.Project id 2 has two children 6 and 9, both project 1 and 3 has one. 编辑:查看祖先列。项目ID 2有两个孩子6和9,项目1和3都有一个。 I need to sort on basic of no of children, ie 2, 1, 3, rest... 我需要在没有孩子的情况下进行排序,即2、1、3,休息... 在此处输入图片说明

This should definitely be possible, you just need to join the two tables in order to use the COUNT of the Project s children. 这绝对应该是可能的,您只需要联接两个表即可使用Project的子项COUNT

Because you didn't include your schema, I made some assumptions about class names and foreign key/primary key names. 因为您不包括架构,所以我对类名和外键/主键名做了一些假设。 My solution assumes the child class has a table name of children, primary key of id, and a foreign key of project_id which references the Project class/projects table. 我的解决方案假定子类具有一个子表名称,id主键和一个引用Project类/ projects表的project_id外键。

Project.joins("LEFT OUTER JOIN children on projects.id = children.project_id") .group("projects.id") .order("count(children.id) desc")

It's necessary to use a LEFT OUTER JOIN in order to include the Project s with zero children. 必须使用LEFT OUTER JOIN才能包含零个孩子的Project

(edit: please add the schema for the child class as well as the class definitions of Project and its child class) (编辑:请添加子类的架构以及Project及其子类的类定义)

EDIT Wed May 20 07:34:58 PDT 2015 EDIT PDT 2015年5月20日星期三07:34:58

If ancestry holds the id of a Project s child Project , a self join would work. 如果祖先持有Project的子Project的ID,则自动联接将起作用。
What is the result of Project.find(6).child_ids ? Project.find(6).child_ids的结果是什么?
What is the result of Project.find(7).child_ids ? Project.find(7).child_ids的结果是什么?
I would expect 2 and 3 respectively. 我分别期望23

Project.joins("LEFT OUTER JOIN projects p1 on projects.id = p1.ancestry .group("projects.id") .order("count(p1.ancestry) desc")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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