地区表:
area
id
pid
name
level
1
0
福建
1
2
1
福州
2
3
2
厦门
2
自连接查询数据:
const area= ctx.model.Area.getTableName('tableName');
ctx.model.Area.hasOne(ctx.model.Area, { as: 'To', foreignKey: 'id' });
const data = await ctx.model.Area.find({
where: {id: 2},
attributes: [ 'id', 'pid', 'level', 'name', [app.Sequelize.literal('To.name'), 'p_name'] ],
include: [
{
model: ctx.model.Area,
as: 'To',
required: true, // true:内连接 false: 左外连接
on: {
id: {
[app.Sequelize.Op.eq]: app.Sequelize.col(`${area}.pid`)
}
},
attributes: []
},
],
raw: true,
});
结果:
{
id: 2,
pid: 1,
level: 2,
name: '福州',
p_name: '福建'
}
不过这样会有个问题,第一次访问正常,第二次就会报别名重复的错误
You have used the alias To in two separate associations. Aliased associations must have unique aliases.
Sequelize4.0大致看了一下没找到查询别名的方法,只能通过属性判断,所以在关联前加一层判断别名是否被占用,以此来解决上面问题
if (!ctx.model.Area.associations || !ctx.model.Area.associations.To) {
ctx.model.Area.hasOne(ctx.model.Area, { as: 'To', foreignKey: 'id' });
}