gpt4 book ai didi

database - 如何通过id关联表

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

如何在 Sequelize 中关联两个表?我试过 belongsTo ,但这不起作用。例子:

第一张表:

users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.TEXT,
type: Sequelize.INTEGER

第二个表:
profiles = sequelize.define('profiles', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
place: Sequelize.TEXT,
phone: Sequelize.INTEGER

协会:
profiles.belongsTo(users, {foreignKey: 'id'});

要求:
users.findOne({
where: {name: 'John'},
include: [{model: db.tables.profiles}]
}).then(function(user_data) {
console.log(user_data);
})

返回的 [Error: profiles is not associated to users!]
我需要返回匹配的“用户”行和表“配置文件”中具有相同 ID 的行。错误在哪里?

最佳答案

您需要为两个表声明关联。从您的架构中,我无法判断联接条件是什么。如果您的配置文件表也有一列 user_id 使得 profiles.user_id = users.id ,那么您可以说以下内容:

users.hasMany(profiles, {
foreignKey: 'id'
});

profiles.belongsTo(users, {
foreignKey: 'user_id'
});

关于database - 如何通过id关联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33022065/

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