我如何从 table 中查询一条记录,并在 sequelize 中从其他两个 table 中获取数据?
How do i query a record from a through table and also get the data from the other two tables in sequelize?
我正在使用 Sequelize,这是我的设置
// Event model
const Event = sequelize.define('event', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
}
/// Company model
const Company = sequelize.define('company', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
});
//CompanyEvent model
const CompanyEvent = sequelize.define('company_event', {
companyId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
eventId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
}, {
tableName: 'company_events'
});
然后是协会声明
Company.belongsToMany(Event, {
through: 'company_events'
});
Event.belongsToMany(Company, {
through: 'company_events'
});
我想要得到的是一个查询,它可以 return 这个或类似的东西,我可以从 company
和 event
table.
{
companyId: 1,
eventId: 1,
company: {
id: 1,
name: 'Some corp',
description: 'Some description',
},
event: {
id: 1,
name: 'Some event',
}
}
我怎样才能达到上述目标?谢谢。
CompanyEvent.belongsTo(Company, {
foreignKey: 'companyId',
as: 'company'
});
CompanyEvent.belongsTo(Event, {
foreignKey: 'eventId',
as: 'event'
});
...
CompanyEvent.findAll({
include: ['company', 'event']
})
我正在使用 Sequelize,这是我的设置
// Event model
const Event = sequelize.define('event', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
}
/// Company model
const Company = sequelize.define('company', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
});
//CompanyEvent model
const CompanyEvent = sequelize.define('company_event', {
companyId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
eventId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
}, {
tableName: 'company_events'
});
然后是协会声明
Company.belongsToMany(Event, {
through: 'company_events'
});
Event.belongsToMany(Company, {
through: 'company_events'
});
我想要得到的是一个查询,它可以 return 这个或类似的东西,我可以从 company
和 event
table.
{
companyId: 1,
eventId: 1,
company: {
id: 1,
name: 'Some corp',
description: 'Some description',
},
event: {
id: 1,
name: 'Some event',
}
}
我怎样才能达到上述目标?谢谢。
CompanyEvent.belongsTo(Company, {
foreignKey: 'companyId',
as: 'company'
});
CompanyEvent.belongsTo(Event, {
foreignKey: 'eventId',
as: 'event'
});
...
CompanyEvent.findAll({
include: ['company', 'event']
})