How to get the primary key attribute name of a model? (waterline ORM)

六眼飞鱼酱① 提交于 2019-12-11 08:15:58

问题


Some of my models do not have id as their primary key, and I need to know the name of the primary key of a given model but I couldn't find a way of doing this. I searched in the waterline docs and source, but all what I found in the their source is that they are using the attributes object definition which is stored in a unaccessible variable in the lib scope.

The "cleaner" way I found to do it for now is like this:

// file: api/libs/model.js
module.exports = {
  //...
  primaryKeyName: function (modelName) {
    var key, attr, pk,
        def = require('../models/' + modelName).attributes;
    for (var key in def.attributes) {
      attr = def.attributes[key];
      if (attr && attr.primaryKey) {
        pk = key;
        break;
      }
    }
    return pk || 'id';
  },
  //...
};

but I feel this is a bit tricky and I am wondering if there wouldn't be a better solution with some hidden/undocumented helper function or method on the model or model instance (ie record)...


回答1:


Ah! I should inspect the model class from the console and I'd have my answer.

Anyway, whoever would be looking for the same info, here it is:

SomeModel.primaryKey; // => 'id' or whatever it is

And voila, as simple!




回答2:


There are a bunch of utilities that can help you with this. Check out sails blueprint files and specifically the actionUtils.js file

api\node_modules\sails\lib\hooks\blueprints



来源:https://stackoverflow.com/questions/26445699/how-to-get-the-primary-key-attribute-name-of-a-model-waterline-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!