Sequelize 如何处理foreignKey有多个

1,136 阅读1分钟

表1 cate

cate1cate2cate1_namecate2_name
12test1test2

表2 seoCate

cateIdtitle
1测试
2测试2

问题:cateId可能是cate1(一级类目),也可能是cate2(二级类目),如果在此时两个表该怎么建立关系 可以在查询的时候做两个表的关联映射

        //position 是1||2  as 也要是变化的不然会报错:You have used the alias cateInfo in two separate associations. Aliased associations must have unique aliases
        const cateInfo = await cate.findAll({
            where: { ['cate' + position]: categoryId },
            include: {
                association: cate.belongsTo(seoCate, {
                    foreignKey: 'cate' + position,
                    targetKey: 'cateId',
                    as: 'cateInfo' + position,
                }),
            },
        });