gpt4 book ai didi

sequelize.js - 包含在带有 Sequelize 的中间表中

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

我有两个具有多对多关系的模型。 UserProject 是另一种模型。

User.belongsToMany(Project, through: UserProject);
Project.belongsToMany(User, through: UserProject);
如果我搜索 UserProject,如何包含 User 或 Project?例如:
UserProject.findAll({ where: { name: 'xxx' }, include: User });
我不能这样做,因为 UserProject 与用户无关。如何使用 User 或 Project 关联实例获取 UserProject 实例?

最佳答案

然后查询将如下所示。

    const UserProject = sequelize.model(`UserProject `)
await UserProject.findAll({
where: {TestColumn: 'abc3'},
raw: true,
include: [User, Project]
}).then(data => {
console.log(data)
})
更多详情,请查看 Sequelize documentation
带有临时数据的整个示例是下一个:
const sequelize = new Sequelize('postgres://<username>:<password>@<host>:<port>/<db_name>')

const defineModelsAndData = async () => {
sequelize.define('User', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
}
}, {
timestamps: false
})
const User = sequelize.model(`User`)

sequelize.define('Project', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
}
}, {
timestamps: false
})
const Project = sequelize.model(`Project`)

await sequelize.define('UserProject', {
UserId: {
type: Sequelize.INTEGER,
allowNull: false,
},
ProjectId: {
type: Sequelize.INTEGER,
allowNull: false
},
TestColumn: {
type: Sequelize.STRING,
allowNull: false
},
AnotherColumn: {
type: Sequelize.STRING,
allowNull: false
}
}, {
freezeTableName: true,
timestamps: false
}).sync()
const UserProject = sequelize.model(`UserProject`)

User.belongsToMany(Project, {through: UserProject})
Project.belongsToMany(User, {through: UserProject})

UserProject.belongsTo(User)
UserProject.belongsTo(Project)

await User.sync()
await Project.sync()

let jane = await User.create({name: 'Jane Doe'})
let bill = await User.create({name: 'Bill Conan'})

let petProject = await Project.create({name: 'petProject'})
let webSite = await Project.create({name: 'web-site'})

jane.addProject(petProject)
bill.addProject(petProject)

bill.addProject(webSite)
}

;(async () => {
await sequelize.authenticate()
await defineModelsAndData()

const UserProject = sequelize.model(`UserProject `)
await UserProject.findAll({
where: {TestColumn: 'abc3'},
raw: true,
include: [User, Project]
}).then(data => {
console.log(data)
})
})()

关于sequelize.js - 包含在带有 Sequelize 的中间表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66976984/

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