egg-sequelize 关联查询请教
发布于 5 年前 作者 littledu 4454 次浏览 来自 问答

或许是 sequelize 基础知识不牢靠,并不关 egg 问题,我先描述一下:

有两个表: brandris, 都是多对多关系,另外还有一个关系表 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

我运行的时候报如下错误: image.png

说我 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是多对多的。

// model/customer.ts
app.model.Customer.belongsToMany(app.model.Label, {through: 'customer_label'});
// model/label.ts
app.model.Label.belongsToMany(app.model.Customer, {through: 'customer_label'});
// 多对多会自动生成customer_label表(包含:customer_id,label_id字段),你再建一个customer_labelmodel去操作这个表就可以了
// service/customer.ts
await app.model.Customer.findAndCountAll({
            where: condition, offset, limit,
            order: orders, attributes: { exclude: ['desc'] },
            include: [{
                model: app.model.Label,
                through: {
                    attributes: ['CustomerId', 'LabelId'],
                }
            }],
        });

brand 和 ris中不用包含外键,做不做不到多对多。

回到顶部