Reputation: 1
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
Reputation: 1
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
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