我如何获得续集模型的主键?

How do i get the primary key of a sequelize model?

基本上,给定一个实例或模型,我想 a) 知道主键是否存在 b) 知道该字段的名称

感谢 Soheil Jadidian 的评论;以下代码段 returns 找到了主键数组。因此,它也适用于复合键。

Model.describe().then(function (schema) {
    return Object.keys(schema).filter(function(field){
        return schema[field].primaryKey;
    });
}).tap(console.log);

看看Model.primaryKeyAttributes,是主键属性的字符串名称数组:

console.dir(Model.primaryKeyAttributes);

[ 'id' ]
  • Model.primaryKeyAttributes - 名称数组
  • Model.primaryKeys - 包含所有数据的对象