mysql怎样统计关联外键的数量,用Sequelize又怎样操作
发布于 7 年前 作者 Mainintowhile 4448 次浏览 来自 问答

/大意如下:(CRM:Sequelize,Promise 流程控制); user instance {id:xx,username:xx}; store instance{id:xx,storename:xx}; 一个user关联多个store; 我想查找user时统计store数量; ------------------------------------------/ user_condition = { include:{ model.user } } model.user.all(user_condition) /输出:/ [{ id:xx, username:xx Stores:[{ id:xx, storename:xx }] }] /怎样统计Stores的数量?/

4 回复

书写格式不好控制,见笑,

建议看一下sequelizejs 文档里的 relations association 这一部分 需要先定义两个表的relation 一对多的话,如果外键userId在Store表,那么用 User.hasMany({model: Store, as: ‘stores’, foreignKey: ‘userId’}); 查询时候使用 User.find({where:{}, include:[{model: Store, as: ‘stores’, where:{deleted: 0}}]

多对多的话可以用 A.hasMany({model: B, as: ‘bs’, through: ‘UserStore’, …

临时写的,可能有错,看看文档吧

@xltank tanks,关联表有的,这里就写了个大意。主要是怎样统计include里面的条目数量。 这两天又发现一个问题,感兴趣的可以攻克攻克:google:“Unknown Column” error in Sequelize when using “limit” and “include” options

回到顶部