egg-sequelize 关联查询请教
发布于 7 年前 作者 littledu 5443 次预览 最后一次回复是 6 年前 来自 问答
或许是 sequelize 基础知识不牢靠,并不关 egg 问题,我先描述一下:
有两个表: brand 和 ris, 都是多对多关系,另外还有一个关系表 ris_to_brand。
brand 表关联写法如下:
Brands.associate = function() {
app.model.Brands.belongsToMany(app.model.Ris, { as: 'bri', through: 'ris_to_brand', foreignKey: 'brand_id' });
};
ris 表关联写法如下:
Ris.associate = function() {
app.model.Ris.belongsToMany(app.model.Brands, { as: 'rib', through: 'ris_to_brand', foreignKey: 'ris_id' });
};
ris_to_brand 表结构分别是 id, ris_id, brand_id。
我运行的时候报如下错误:
说我 ris_to_brands 表不存在,按我的理解,我指定的是 through: ris_to_brand ,怎么会去寻找 ris_to_brands 这个名称的表呢?
不明白。
6 回复
through: app.model.ris_to_brand
解决了,是 sequelize 默认会把表名转为复数,所以,如果想自己定义,可以 model 定义时加
freezeTableName: true即可想问下那个association建立是 A,C通过B对应多对多 A,C,B三个表之间的连接字段是必须要一致吗?如果不一致的话怎么办呢?
我不用关联查询,都是挨个查表,然后再组合,有没有大佬说一下,这种性能会差一些吗
直接上例子 Customer和label是多对多的。
brand 和 ris中不用包含外键,做不做不到多对多。