gpt4 book ai didi

postgresql - 使用belongsToMany时在sequelize中获取 "model is not associated with other Model"

转载 作者:行者123 更新时间:2023-12-03 22:29:00 25 4
gpt4 key购买 nike

我正在使用 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 架构如下:
    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
}

我正在使用 belongsToManysequelize 并创建第三个表名称 UserLocation,其中我已经提到了 belongsToManyUserLocation,如下所示:
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
});

在执行上述代码时,我收到以下错误:

User Model is not associated with 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
});

关于postgresql - 使用belongsToMany时在sequelize中获取 "model is not associated with other Model",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32047567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com