gpt4 book ai didi

database - Sequelize 字段关联不起作用

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

我有两张 table 。如何将第一个表中的字段与 Sequelize 中第二个表中的 id 字段链接起来?

第一张表:

tables.comments = sequelize.define('comments', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
text: Sequelize.TEXT,
article: Sequelize.INTEGER,
author: {
type: Sequelize.INTEGER,
references: "users",
referencesKey: "id",
allowNull: false
},
answer: Sequelize.INTEGER,
rating: {
type: Sequelize.INTEGER,
defaultValue: 0
}
}, {
classMethods: {
associate: function(models) {
tables.comments.belongsTo(tables.models.users, {foreignKey: 'author', targetKey: 'name'});
}
}
});

第二个表:
tables.users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
mail: Sequelize.TEXT,
name: Sequelize.TEXT,
pass: Sequelize.TEXT,
status: {
type: Sequelize.INTEGER,
defaultValue: 0
},
rating: {
type: Sequelize.INTEGER,
defaultValue: 0
},
ban: {
type: Sequelize.INTEGER,
defaultValue: 0
},
key: Sequelize.TEXT
}, {
classMethods: {
associate: function(models) {
tables.users.hasMany(tables.models.comments, {foreignKey: 'author'});
}
}
});

我需要获取tables.comments,但是tables.users 的作者姓名不是“作者”。我提出要求:
tables.comments.findAll({inclide: [{model: tables.users}]}).then(function(comments) {
console.log(comments);
});

但结果字段 author 只有数字,而不是来自 users 的名称!
错误在哪里?

(抱歉英语不好)

最佳答案

在关联类方法中,您需要使用定义类方法的表的列名。我假设连接条件是 comments.author = users.id

对于您的评论表,它将是:

tables.comments.belongsTo(tables.models.users, {
foreignKey: 'author'
});

对于您的用户表,它将是:
tables.users.hasMany(tables.models.comments, {
foreignKey: 'id'
});

关于database - Sequelize 字段关联不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854133/

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