0

I use Knex/Objection with PostgreSQL and I'm trying to update the foreign key but it returns null without any error.

Car model:

export class CarModel extends Model implements Car {
  public static readonly tableName: string = 'cars';
  public static readonly idColumn: string = 'car_id';

  public static readonly jsonSchema: object = {
    type: 'object',
    properties: {
      name: { type: 'string' },
      carBrandId: { type: ['number', 'null'] },
      lastUpdated: { type: ['string', 'null'], format: 'date-time' }
    }
  };

  public static readonly relationMappings: RelationMappings = {
    carBrandId: {
      relation: Model.BelongsToOneRelation,
      modelClass: 'brand.model',
      join: {
        from: 'brands.brand_id',
        to: 'cars.fk_cars_brands'
      }
    }
  };

  public carId: number;
  public name: string;
  public carBrandId: number;
}

Creation of cars table:

import { Knex } from 'knex';

export function up(knex: Knex): Promise<boolean | void> {
  return knex.schema.hasTable('cars').then(function(exists) {
    if (!exists) {
      return knex.schema.createTable('cars', (table) => {
        table.specificType('car_id', 'INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY');
        table.specificType('name', 'TEXT').notNullable();
        table.specificType('car_brand_id', 'INTEGER').references('brand_id').inTable('brands').withKeyName('fk_cars_brands');
        table.specificType('last_updated', 'TIMESTAMP');
      });
    }
  })
}

export function down(knex: Knex): Knex.SchemaBuilder {
  return knex.schema.dropTableIfExists('cars');
}

And then I use patch method in my service to update car_brand_id value from default to new added brand:

Database.getConnection().then((connection) => {
  return CarModel.query(connection)
    .patch({
       carBrandId: 1, // row with brandId=1 exists in table brands!
       lastUpdated: new Date().toISOString()
     })
     .where('carId', 10)
     .returning('*')
     .first()
});

And it returns the row where lastUpdated was updated, but carBrandId is still null:

{ carId: 10, name: 'Ferrari', carBrandId: null, lastUpdated: '<some date>' }

I would appreciate any help!

blackhard
  • 502
  • 7
  • 26

0 Answers0