简体   繁体   English

按一对多关系中的子代数排序查询

[英]Sequelize sort query by number of children in one-to-many relationship

Let's say I have a model Parent that belongsToMany Children. 假设我有一个模型Parent,它属于ManyChilds。 I want to query some parent objects, and sort them so that instances of parent with the most children come first. 我想查询一些父对象,并对它们进行排序,以使子对象最多的父实例排在第一位。

Likewise, is it possible to append other conditions to the children that are counted? 同样,是否可以将其他条件附加到被计数的孩子身上? For example, sorting parents by the number of female children under the age or 3. 例如,按年龄在3岁以下的女童的数量对父母进行排序。

What is an efficient way to accomplish this? 有什么有效的方法可以做到这一点?

You can add child count pre-calculation field to the parent so u will never need to go to children object and this will make quaring very fast, also when you add a new child/delete child keep remember to increase or decrease the value in the parent. 您可以向父级添加子项计数预计算字段,这样您就无需再访问子级对象,这将使隔离非常快,而且在添加新的子项/删除子项时,请记住要增加或减少子项中的值。父母

same in the second question add tow field into parent male_child_count & female_child_count, life will be more easier :-) 在第二个问题中相同,将拖曳字段添加到父male_child_count和female_child_count中,生活会更容易:-)

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

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