简体   繁体   中英

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

Let's say I have a model Parent that belongsToMany Children. 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.

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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