动态获取模型的外键列名称

时间:2017-01-13 12:03:45

标签: javascript node.js express sequelize.js

我在用户和团队之间定义了两个模型和HasMany关系。我的最终代码是这样的:

app.listen(3000, function () {
    sequelize = new Sequelize('mysql://username:password@localhost:3306/restful_api_demo');

sequelize
    .authenticate()
    .then(function (err) {
        console.log('Connection has been established successfully.');
        User = sequelize.define('users', {
            firstName: { type: Sequelize.STRING },
            lastName: { type: Sequelize.STRING }
        });

        Team = sequelize.define('teams', {
            teamName: { type: Sequelize.STRING },
            projectName: { type: Sequelize.STRING }
        });

        Team.hasMany(User, { foreignKey: 'teamId' });

        //get all model names into an array
        var modelObj = sequelize.models;
        for (var key in modelObj) {
            var value = modelObj[key];
            models.push(value);
        }

        models.forEach(function (m) {
            // Read the model name
            var modelName = m.getTableName();

            var assotions = m.associations;
            for (key in assotions) {
                var assotionType = assotions[key].associationType;
                var assoModel = sequelize.model(key);
                app.get('/' + modelName + '/:id/' + key, function (req, res) {
                    var id = req.params.id;
                    assoModel.findAll(
                        {
                            where: { teamId: id }
                        }).then(function (i) {
                            res.json(i);
                        });
                });
            }
        })
    })
    .catch(function (err) {
        console.log('Unable to connect to the database:', err);
    });
});

它从此URL提供以下json结果。 http://localhost:3000/teams/1/users

[
    {
        "id": 1,
        "firstName": "John1",
        "lastName": "Hancock1",
        "createdAt": "2017-01-12T07:06:53.000Z",
        "updatedAt": "2017-01-12T07:06:53.000Z",
        "teamId": 1
    },
    {
        "id": 2,
        "firstName": "John2",
        "lastName": "Hancock2",
        "createdAt": "2017-01-12T07:18:48.000Z",
        "updatedAt": "2017-01-12T07:18:48.000Z",
        "teamId": 1
    }
]

我修改了获取查询外键的代码。

  var foreign = assotions[key].foreignKey;
  var assoModel = sequelize.model(key);
  app.get('/' + modelName + '/:id/' + key, function (req, res) {
    var id = req.params.id;
    assoModel.findAll({
      where: {foreign: id}
    }).then(function (i) {
      res.json(i);
    });
  });

它给出了这个错误。

Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'users.foreign' in 'where clause'

如何获取此变量的值而不是变量名?

1 个答案:

答案 0 :(得分:1)

关联有'associationType'方法但也有 foreignKey 方法

...
var foreign = assotions[key].foreignKey;
var query = {
  [foreign]: id // value you want
}
...
assoModel.findAll({
  where: query
}).then(function (i) {
  res.json(i);
});