首页 > 解决方案 > Knex/反对关系“一对多”

问题描述

我有一个具有类别关系的产品。每个产品可以有多个类别。
问题:我需要设计一个关系以包含产品具有“所有类别”关系的情况。我可以将关系添加到所有类别,但如果类别列表将被更新,“所有类别”将被损坏。产品:

id | name
1  | product1
2  | product2
3  | product3

产品类别:

id | product_id | category_id
1  |  1         |   1
1  |  1         |   2
1  |  2         |   2
4  |  3         |   3

类别:

id | name
1  | one
2  | two
3  | three

异议积关系映射:

static relationMappings = {
    categories: {
      relation: Base.ManyToManyRelation,
      modelClass: path.resolve(__dirname, 'Category'),
      join: {
        from: 'products.id',
        through: {
          from: 'product_categories.product_id',
          to: 'product_categories.category_id',
        },
        to: 'categories.id',
      },
    },

标签: sqldesign-patternsknex.jsobjection.js

解决方案


推荐阅读