简体   繁体   中英

Sort array by length in sequelize

I use "sequelize". In the array, I store user ids. I need to sort by the number of elements in the array, that is, the more elements in the array, the higher it is in the list, the elements inside the array are not interesting to me.

return db.Books.findAll({
    limit: 5,
    include: [{
        model: db.User
    }],
    order: [
        ['likes']    // likes it's array
    ]
})

};

To get a list of books ordered by the amount of some arbitrary model instances associated with it, let's assume Like , you can use a function to count the rows in Like that match the relation:

return db.Books.findAll({
    limit: 5,
    include: [{
        model: db.User
    },
    {
        model: db.Like,
        attributes:[
            [Sequelize.fn('COUNT', '*'), 'num_of_likes']
        ]
    }],
    order: [
        ['num_of_likes']    // likes it's array
    ]
});

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