Alias for the associated models using Sequelize typescript

1.8k views Asked by At

I have two models Company and Reviews. Each Company will have multiple Reviews.

This is the Company model

@Table()
export class Company extends Model<Company> {

  @Column({ type: DataType.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true })
  COMPANY_ID: number;

  @Column({ type: DataType.TEXT })
  Name: string;

  @HasMany(() => Review)
  reviews: Review[];
}

The Reviews model is as follows

@Table()
export class Review extends Model<Review> {
  @Column({ type: DataType.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true })
  REVIEW_ID: number;

  @ForeignKey(() => Company)
  @Column
  Company_ID: number;

  @Column({ type: DataType.TEXT })
  Review: string;

  @Column({ type: DataType.INT })
  rating: string;

  @Column({ type: DataType.TEXT })
  UserName: string;

  @BelongsTo(() => Company)
  Company: Company;
}

I am trying to fetch the list of all the reviews present for a company. The query I have written so far is

    const pagedData = await Review.findAndCountAll({
      attributes: [
        ['REVIEW_ID', 'id'],
        ['Review', 'feedback']
      ],
      include: [{
        model: Company,
        attributes: ['Name']
      }],
      limit,
      offset
    });

The response I get back is

{
  "total": 2,
  "reviews": [
    {
      "id": 917004723,
      "feedback": "feedback 1",
      "company": {
        "Name": "www.acceleronpharma.com"
      }
    },
    {
      "id": 917004734,
      "feedback": "feedback 2",
      "company": {
        "Name": "http://www.accenture.com"
      }
    }
  ]
}

Questions:

  1. Is there a way to add an alias for the associated model? Like instead of Name in the Company I would want it to be companyName or something else.
  2. Instead of pulling it out as an object within the reviews array is it possible to pull it out as a property in the review object itself.
    {
      "id": 917004723,
      "feedback": "feedback 1",
      "companyName": "www.acceleronpharma.com"
    }

PS: Please ignore the casing, I just added an example of the issue I am facing.

0

There are 0 answers