使用belongsToMany时,在sequelize中获取“模型与其他模型无关”

时间:2015-08-17 10:00:55

标签: postgresql many-to-many sequelize.js

我正在使用sequelize postgreSQL。我有两个模式,即UserLocationUser可以包含多个Locations,而Location可以包含多个Users

我的User架构如下

    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: Sequelize.STRING,
        require: true
    },
    middleName: {
        type: Sequelize.STRING,
        require: false
    },
    lastName: {
        type: Sequelize.STRING,
        require: true
    },
    age: {
        type: Sequelize.INTEGER,
        require: false
    },
    email_Id: {
        type: Sequelize.STRING,
        require: true,
        unique: true,
        validate: {
            isEmail: true
        }
    }

我的Location架构如下:

    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    latitude: {
        type: Sequelize.DOUBLE,
        require: true
    },
    longitude: {
        type: Sequelize.DOUBLE,
        require: true
    },
    locationAddress: {
        type: Sequelize.STRING
    },
    mailBoxNo: {
        type: Sequelize.INTEGER
    }

我正在使用belongsToMany sequelize并创建第三个表名UserLocation,其中我提到belongsToManyUser Location如下:

User.belongsToMany(Location, {
    through: 'UserLocation'
});
Location.belongsToMany(User, {
    through: 'UserLocation'
});

我的要求是获取给定locations个ID的所有user。我的守则如下:

    var param = req.body;
    var options = {};
    if (param.where) {
        options.where = param.where;
    }
    options.include = [{
        model: User  //User Model
    }, {
        model: Location  //Location Model
    }];

    //Here userLocation refers to UserLocation Schema
    userLocation.findAll(options).then(function (response) {
             //Some Logic
        }).catch(function (err) {
            //Error handling
        });

执行上面的代码时,我收到以下错误:

  

用户模型与UserLocation模型无关。

我无法理解为什么会出现以下错误。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用它来获取给定用户的所有位置;

User
  .findOne({
    "where": {
      "id": param.where
    },
    "include": [Location]
  })
  .then(function(user) {
    // should get this user
    console.log(user);

    // should get all locations of this user
    console.log(user.Locations);
  })
  .catch(function(error) {
    // error handling
  });