Bartłomiej Pachel
Bartłomiej Pachel

Reputation: 1

Typeorm: How to order by date in relation one to many

I have a Devices entity and a related Data entity

Devices entity

export class Devices extends BaseEntity{

    @PrimaryColumn()
    id_device: number;

    @Column("varchar", { length: 50 , default: "---"})
    name: string;

    @Column("varchar", { length: 50 , default: "---" })
    address: string;

    @Column({default: false})
    shared: boolean;

    @OneToMany(() => Data, data => data.id_data)
    Data: Data[];
}

Data entity

export class Data extends BaseEntity{

    @PrimaryGeneratedColumn()
    id_data: number;

    @Column()
    temperature: number;

    @Column({nullable: true})
    id_device: number;

    @CreateDateColumn()
    time;

    @ManyToOne(()=>Devices, devices => devices.id_device,{
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    })
    @JoinColumn({name: "id_device"})
    devices: Devices;

}

I would like to get all the latest Data entries for which Devices has shared set to true.

How can I do this using QueryBuilder?

Upvotes: 0

Views: 13345

Answers (2)

Here is how you can do it without using a query builder.

const dataRepository = AppDataSource.getRepository(Data);

const dataItems = dataRepository.find({
  where: {
    device: {
      sharedDevice: true
    }
  },
  relations: {
    devices: true
  }
  data: {
    time: "DESC"
  }
})

Upvotes: 0

hp10
hp10

Reputation: 632

If device can have many data entries, and data can have many devices, it should be ManyToMany relation.

Here's the approach with query builder:

const data = await this.createQueryBuilder("data")
    .leftJoin("data.devices", "device")
    .where("device.shared = :sharedDevice", { sharedDevice: true })
    .orderBy("time", "DESC")
    .getMany()

Upvotes: 2

Related Questions