我知道有一大堆这样的问题,我尝试了许多解决方案,我可以找到,但似乎没有为我工作。
我有两个模型,Player和PlayerSkill。
玩家:
import Sequelize from 'sequelize';
import database from '../index';
const Player = database.define(
'player',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: Sequelize.STRING(200),
allowNull: false,
},
position: {
type: Sequelize.STRING(200),
allowNull: false,
},
},
{
timestamps: false,
}
);
Player.associate = models => {
models.Player.hasMany(models.PlayerSkill, {
as: 'playerskills',
foreignKey: 'playerId',
});
};
export default Player;
我的PlayerSkill模型:
import Sequelize from 'sequelize';
import database from '../index';
const PlayerSkill = database.define(
'playerSkill',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
skill: {
type: Sequelize.STRING(200),
allowNull: false,
},
value: {
type: Sequelize.INTEGER,
},
playerId: {
type: Sequelize.INTEGER,
allowNull: false,
},
},
{
timestamps: false,
}
);
PlayerSkill.associate = models => {
models.PlayerSkill.belongsTo(models.Player, {
foreignKey: 'playerId',
allowNull: false,
});
};
export default PlayerSkill;
我需要以如下方式获取数据:
{
"id": 1,
"name": "player name 2",
"position": "midfielder",
"playerSkills": [
{
"id": 1,
"skill": "attack",
"value": 60,
"playerId": 1
},
{
"id": 2,
"skill": "speed",
"value": 80,
"playerId": 1
}
]
}
下面是我的fetch函数:
// Create new player
await Player.create(req.body)
.then(() => {
PlayerSkill.bulkCreate(skills);
})
.then(() => Player.findAll({ include: ['playerskills'] }))
.then(result => console.log(result))
.catch(err => {
res.status(400).send({
message: err.message || 'Error occurred while creating player',
});
});
Postman 要求:
{
"name": "player1",
"position": "defender",
"playerSkills": [
{
"skill": "strength",
"value": 90,
"playerId": 1
},
{
"skill": "speed",
"value": 90,
"playerId": 1
}
]
}
我不明白我在这里做错了什么。我一直得到以下错误:
{
"message": "Association with alias \"playerskills\" does not exist on player"
}
1条答案
按热度按时间pcrecxhr1#
你应该把
Player
模块中hasMany
的直接调用转换成associate
方法,就像你在PlayerSkill
模型模块中一样。不要忘记从Player
模块中删除PlayerSkill
导入行。model/player.js
确保在两个配对的关联中有相同的
foreignKey
选项。并使用来自一个已经定义的模块index
的模型: