如何获取模型的主键属性名称?(水线 ORM) [英] How to get the primary key attribute name of a model? (waterline ORM)

查看:42
本文介绍了如何获取模型的主键属性名称?(水线 ORM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些模型没有 id 作为它们的主键,我需要知道给定模型的主键的名称,但我找不到这样做的方法.我在 waterline 文档和源代码中进行了搜索,但我在他们的源代码中发现的所有内容是,它们使用的是存储在无法访问的变量中的 attributes 对象定义库范围.

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)...

推荐答案

有很多实用程序可以帮助您解决这个问题.查看sails蓝图文件,特别是actionUtils.js文件

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

api\node_modules\sails\lib\hooks\blueprints

这篇关于如何获取模型的主键属性名称?(水线 ORM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆