一对一: belongsTo
一对多: hasMany
Adbook.associate = function () {
// 一对多 { foreignKey: 别的表 '使用什么字段关联'。 targetKey (自己表) ‘只能对自己表ID 参数’}
app.model.Adbook.hasMany(app.model.Adswiper, {
as: 'swiperlist',
foreignKey: 'mid'
})
/**
* User.belongsTo(关联的模型, { foreignKey:自己表 '使用什么字段关联', targetKey: 别的表'与关联的模型那个字段关联', as: '别名' });
*/
// 一对一
// app.model.Adbook.belongsTo(app.model.Adswiper, {
// foreignKey: 'mid',
// targetKey: 'id',
// as: 'swiperlist'
// })
}
查询方法
const result = await ctx.model.Adbook.findAndCountAll({
limit: toInt(limit),
offset: toInt((+currentPage - 1) * +limit),
include: [
{
model: Adswiper,
as: 'swiperlist',
attributes: ['data']
}
],
distinct: true
})