Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sequelize.js

Basically, given an instance or a model, I would like to a) Know if a primary key exists b) know the name of that field(s)

like image 789
Angel S. Moreno Avatar asked Sep 04 '15 19:09

Angel S. Moreno


1 Answers

Thanks to Soheil Jadidian's comment; the following snippet returns an array of primary keys found. Thus, it works with composite keys as well.

Model.describe().then(function (schema) {
    return Object.keys(schema).filter(function(field){
        return schema[field].primaryKey;
    });
}).tap(console.log);
like image 124
Angel S. Moreno Avatar answered Oct 24 '22 02:10

Angel S. Moreno