使用属于时获得续集"model is not associated with other Model"



我使用sequelizepostgreSQL。我有两个图式,即UserLocation。一个User可以有多个Locations,一个Location可以有多个Users

我的User Schema如下

    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 Schema如下:

    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
    }

我正在使用sequelizebelongsToMany并创建第三个表名称UserLocation,其中我已经为UserLocation提到了belongsToMany,如下所示:

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

我的要求是获得给定user id的所有locations。我的代码如下:

    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
        });
在执行上面的代码时,我得到了以下错误:

User Model与UserLocation Model没有关联

我无法理解为什么我得到以下错误。有人能帮我一下吗?

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

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
  });

相关内容

最新更新