1

Hello I'm a beginner with Objection js / Knex. I have an entity Item which relates to another entity Bag I want to insert an Item into a Bag and also update the weight of the bag according to the weight of the Item.

Item class:

 
  id!: Id;
  weight!: number;
  bagId?: Id;
  bag!: Bag;

  static tableName = 'items';

  static get relationMappings(): RelationMappings {
    return {
      bag: {
        relation: Base.BelongsToOneRelation,
        modelClass: 'Bag',
        join: {
          from: 'items.bagId',
          to: 'bags.id',
        },
      },
    };
  }

Bag class:

id!: Id;
  totalWight!: number;
  items?: Item[] | undefined;

  static tableName = 'bags';

  static get relationMappings(): RelationMappings {
    return {
      cuboids: {
        relation: Base.HasManyRelation,
        modelClass: 'Item',
        join: {
          from: 'bags.id',
          to: 'items.bagId',
        },
      },
    };
  }

I've already used upsertGraph and trie using patchAndFetchById but all of these seem to hang when I try to update the parent (Bag) and also insert the Item value.

WilsonPena
  • 1,451
  • 2
  • 18
  • 37

1 Answers1

0

You can use Instance Methods of objection. Like $beforeInsert() or $afterInsert()

Here an example of this with $afterInsert():

async $afterInsert(queryContext: QueryContext): Promise<void> {
    await super.$afterInsert(queryContext);

    await Bag.query()
      .update({
        totalWight: totalWight + this.weight,
      })
      .where('id', this.bagId);

}

Keep in mind that this $afterInsert() should be added in Item class and I'm assuming that Item class extends Model class from objection