使用 knexjs 和 objection 在 express ts 中获取关系对象

Get relation object in express ts with knexjs and objection

提问人:Fadhlih Girindra Putra 提问时间:11/18/2023 最后编辑:possumFadhlih Girindra Putra 更新时间:11/20/2023 访问量:10

问:

我使用带有 knexjs 和 Objection 的 Express TS。 我只想获取每辆车的名称Brand、carType、carTransamission。因为我想将数据传递到 DTO。但是我得到了这样的错误:

属性“carBrand”在类型“CarModel”上不存在。你的意思是“carBrandId”吗?

这是我的CarModel:

export class CarModel extends Model {
  id!: string;
  name!: string;
  price!: number;
  year?: number;
  capacity!: number;
  description?: string;
  pictureUrl!: string;
  availableAt?: Date;
  createdAt!: Date;
  updatedAt!: Date;
  isDeleted!: boolean;
  deletedAt?: Date;
  carBrandId?: string;
  carTransmissionId?: string;
  carTypeId?: string;

  static relationMappings = {
    carBrand: {
      relation: Model.BelongsToOneRelation,
      modelClass: CarBrandModel,
      join: {
        from: "car.carBrandId",
        to: "car_brand.id",
      },
    },
    carTransmission: {
      relation: Model.BelongsToOneRelation,
      modelClass: CarTransmissionModel,
      join: {
        from: "car.carTransmissionId",
        to: "car_transmission.id",
      },
    },
    carType: {
      relation: Model.BelongsToOneRelation,
      modelClass: CarTypeModel,
      join: {
        from: "car.carTypeId",
        to: "car_type.id",
      },
    }
  };

  static get tableName() {
    return "car";
  }
}

export type Car = ModelObject<CarModel>;

我已经按照 knexjs 文档进行了操作,我想像这样获得 carBrand:

let car2 = await CarModel.query().first().withGraphFetched('carBrand');
    console.log(car2.carBrand.name)
TypeScript PostgreSQL Express Knex.js 异议.js

评论


答: 暂无答案