sequelize association - 订单与用户

时间:2017-04-17 15:09:07

标签: javascript express sequelize.js

在购物车管理系统中, 用户有许多订单,订单属于用户,在这种情况下,userID('用户'表的PK)在'订单'表中是FK。 我尝试了这个,但这给出了关联错误,即订单与用户无关。

 db.user.findAll({
    include: [
      {
        model: db.order
      }
    ]
  })
    .then(users => {
      res.json(users)
    });

以下是模型: -

订单: -

'use strict';
var db = require('../models/index');

module.exports = function (sequelize, DataTypes) {
  var order = sequelize.define('order', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    totalAmount: {
      type: DataTypes.INTEGER,
      allowNull: false
    }
    ,
    createdAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
      classMethods: {
        associate: function (models) {
          order.belongsTo(models.user);
          order.belongsToMany(models.products, { through: { model: models.orderProduct } });
          // order.hasMany(models.orderProduct);
        }
      }
    });
  return order;
};

用户: -

'use strict';
var db = require('../models/index');

module.exports = function (sequelize, DataTypes) {

  var user = sequelize.define('user', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    address: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    contact: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    type: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
  }, {
      activated: {
        type: DataTypes.BOOLEAN,
        allowNull: true
      }
    }, {
      classMethods: {
        associate: function (models) {
          user.hasMany(models.order);
        }
      }
    });
  return user;
};

这是错误: -

Unhandled rejection Error: order is not associated to user!
    at Model.validateIncludedElement (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\sequelize\lib\model.js:558:11)
    at F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\sequelize\lib\model.js:440:29
    at Array.map (native)
    at Model.validateIncludedElements (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\sequelize\lib\model.js:436:37)
    at Model.<anonymous> (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\sequelize\lib\model.js:1372:32)
    at Model.tryCatcher (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\promise.js:693:18)
    at Async._drainQueue (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (F:\UNI\BSCS -VII\IAD\WebProjects\Project\SERVER\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)

2 个答案:

答案 0 :(得分:1)

指定您的外键。您正在使用的那些密钥不会自动推断出来。

order.belongsTo(models.user, {foreignKey: 'userID'});
..
user.hasMany(models.order, {foreignKey: 'userID'});
编辑:我重新检查了你的帖子,你的用户定义方式错误。您的最后一个字段“已激活”在外面,关闭上一个对象。这就是为什么它没有阅读你的联想。

    updatedAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
  }, {
      activated: {
        type: DataTypes.BOOLEAN,
        allowNull: true
      }
    }, {
      classMethods: {
        associate: function (models) {
          user.hasMany(models.order);
        }
      }
    });

应该是:

        updatedAt: {
          type: DataTypes.DATE,
          allowNull: true
        },
        activated: {
            type: DataTypes.BOOLEAN,
            allowNull: true
          }
      }, {
          classMethods: {
            associate: function (models) {
              user.hasMany(models.order);
            }
          }
        });

答案 1 :(得分:0)

试试这个。 像这样修改您的关联:

order.belongsTo(models.user, {as : 'User'});

user.hasMany(models.order, {as : 'Orders'});

在查询时:

db.user.findAll({
include: [{model: db.order, as: 'Orders'}]
})
.then(users => {
  res.json(users)
});