【问题标题】:Get belongsToMany association based on postgresql schema基于postgresql模式获取belongsToMany关联
【发布时间】:2022-01-26 19:52:09
【问题描述】:

我正在使用 Expressjs、Sequelize(sequelize-typescript) 和 Postgresql 构建一个多租户应用程序,但在获取表与数据库模式的关联时遇到了问题。

我有 2 个架构(比如说法国和意大利)。一切正常(我可以得到 belongsTo 关联、hasMany 关联等),除了获取 belongsToMany 关系,因为 sequelize 没有从关联表的正确模式中选择。

这是我的模型:

//Shop Model

@Table({ timestamps: true, tableName: 'shops' })
export class Shop extends Model<Shop> {

    @AllowNull(false)
    @Column
    name!: string;

    @BelongsToMany(() => Category, () => ShopCategory)
    categories!: Category[];
}


// Category

@Table({ timestamps: true, tableName: 'categories' })
export class Category extends Model<Category> {

    @AllowNull(false)
    @Column
    name!: string;

    @BelongsToMany(() => Shop, () => ShopCategory)
    shops!: Shop[];
}


// ShopCategory

@Table({ timestamps: true, tableName: 'shop_categories' })
export class ShopCategory extends Model<ShopCategory> {

    @ForeignKey(() => Shop)
    @Column
    shopId!: number;

    @ForeignKey(() => Category)
    @Column
    categoryId!: number;
}

这是续集查询:

userEntity.schema('france').findOne({
   attributes: ['id'],
   where: { id: user.id },
   include:
       [{
           model: shopEntity.schema('france'),
           where: { statusId: 2 },
           include:
           [{
               model: categoryEntity.schema('france')
           }]
       }]
});

上面的查询从 france.users、france.shops 和 france.categories 中选择,但不是从 france.shop_categories 中选择(对于此关联,它使用默认模式)。

我如何告诉 sequelize 从正确的模式中为 belongsToMany 关联选择?

【问题讨论】:

    标签: node.js postgresql sequelize.js sequelize-typescript


    【解决方案1】:

    尝试明确指出schema 选项:

    @Table({ timestamps: true, tableName: 'shop_categories', schema: 'italy' })
    

    【讨论】:

      猜你喜欢
      • 2017-02-16
      • 1970-01-01
      • 2017-03-02
      • 2020-06-25
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多