dimanche 22 décembre 2019

Knex/Objection relation "One to Many"

I have a product that has a category relationship. Each product can have multiple categories.
The problem: I need to design a relationship to include the case when a product has "All Categories" relation. I can add relations to all categories but if the category list will be updated "All categories" will be corrupted. product:

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

product_categories:

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

categories:

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

Objection product relation mappings:

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',
      },
    },

Aucun commentaire:

Enregistrer un commentaire