所以仍然试图弄清楚如何使用关联和 Sequelize 。我正在尝试关联具有多个团队的游戏。
游戏:
"use strict"
module.exports = (sequelize, DataTypes) => {
var game = sequelize.define('game', {
gameId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
awayTeam: {
type: DataTypes.INTEGER,
references: {
model: "team",
key: 'teamId',
},
allowNull: false
},
homeTeam: {
type: DataTypes.INTEGER,
references: {
model: "team",
key: 'teamId',
},
allowNull: false
},
awayTeamScore: {
type: DataTypes.INTEGER,
allowNull: false
},
homeTeamScore: {
type: DataTypes.INTEGER,
allowNull: false
},
},
{
timestamps: false,
tableName: 'game',
associate: function (models) {
/// trying to figure this out
}
}
);
return game;
};
团队:
"use strict"
module.exports = (sequelize, DataTypes) => {
var team = sequelize.define('team', {
teamId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
city: {
type: DataTypes.STRING,
allowNull: false
}
},
{
timestamps: false,
tableName: 'team',
associate: function(models){
/// trying to figure this out
}
}
);
return team;
};
会不会是团队属于许多游戏而游戏有很多团队?
最佳答案
您需要在 hasMany()
类方法中使用 associate()
函数。
游戏:
"use strict";
var game = {};
var classmethods = {};
module.exports = (sequelize, DataTypes) => {
game = sequelize.define('game', {
gameId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
awayTeam: {
type: DataTypes.INTEGER,
references: {
model: "team",
key: 'teamId',
},
allowNull: false
},
homeTeam: {
type: DataTypes.INTEGER,
references: {
model: "team",
key: 'teamId',
},
allowNull: false
},
awayTeamScore: {
type: DataTypes.INTEGER,
allowNull: false
},
homeTeamScore: {
type: DataTypes.INTEGER,
allowNull: false
},
},
{
timestamps: false,
classmethods: classmethods
}
);
return game;
};
classmethods.associate = function (models) {
game.hasMany(models.team, {foreignKey: 'teamId'});
};
为此,您还需要以这种方式设置 Sequelize:
https://github.com/jklepatch/kangaroojs/blob/master/apps/web/models/index.js
如果您还希望能够使用团队模型中的关联,则需要在团队模型中使用 'belongsTo()`
"use strict";
var team;
var classmethods;
module.exports = (sequelize, DataTypes) => {
team = sequelize.define('team', {
teamId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
city: {
type: DataTypes.STRING,
allowNull: false
}
},
{
timestamps: false,
tableName: 'team',
classmethods: classmethods
}
);
return team;
};
classmethods.associate = function (models) {
game.belongsTo(models.game);
};
关于sql - Node JS Sequelize sql 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426375/