如何联接两个表? -无法读取未定义的属性“ getTableName”

时间:2019-02-17 15:02:00

标签: node.js sequelize.js

用户模型文件

'use strict';
module.exports = (sequelize, DataTypes) => {
  const user = sequelize.define('user', {
    "access_role_id":DataTypes.INTEGER,
    "user_type":{
      type:   DataTypes.ENUM,
      values: ['A', 'V', 'U']
    },
    "login_access":{
      type:   DataTypes.ENUM,
      values: ['APP', 'WEB', 'BOTH']
    },
    "username": DataTypes.STRING,
    "email": DataTypes.STRING,

    "updated_at":DataTypes.DATE,
    "created_at":DataTypes.DATE,
  }, {
    "timestamps": false,
    "createdAt": false,
    'updatedAt': false,
    "underscored": true,
    "freezeTableName": false,
  });
  user.associate = function(models) {
    // associations can be defined here
    models.user.belongsTo(models.product, {targetKey: 'id',foreignKey: 'created_by'});
  };
  return user;
};

用户控制器文件

const dbConfig = require( '../../../db/models/index');
let users =require('../../../db/models/user')(dbConfig.sequelizeDB,dbConfig.Sequelize);
module.exports = {
  // GET /customer/:id
  getCustomer: function(req, res, next) {
    users.findAll({
      include: [{
        model: users.product,
      }]
    }).then(function (stores) {
      if (stores.length === 0) {
        res.json('There are no stores in the database');
      }
      res.json(stores);
    });
  },
};

我无法获取product表数据。它总是显示错误:

  

未处理的拒绝TypeError:无法读取未定义的属性'getTableName'。

为什么在用户模型中未提取product表?如何通过用户模型访问此产品表数据?

1 个答案:

答案 0 :(得分:0)

将您的用户控制器文件更新为

    const dbConfig = require( '../../../db/models/index');
    let users =require('../../../db/models/user')(dbConfig.sequelizeDB,dbConfig.Sequelize);
    let product=require('../../../db/models/product')(dbConfig.sequelizeDB,dbConfig.Sequelize);
    module.exports = {
      // GET /customer/:id
      getCustomer: function(req, res, next) {
        users.findAll({
          include: [{
            model: product,
          }]
        }).then(function (stores) {
          if (stores.length === 0) {
            res.json('There are no stores in the database');
          }
          res.json(stores);
        });
      },
    };