How to populate (join) tables in Nestjs + mysql

Viewed 16

I have one to many relationship. What I'm trying to do is when I call Group all query. I want in devices keys have all POPULATED devices. How should I set my models ?

I have 2 models

  1. Group

     import Device from "src/device/device.model";
    
     interface GroupCreateAttrs {
         name: string,
         desctiption: string
     }
    
     @Table({tableName: "groups"})
     export default class Group extends Model<Group, GroupCreateAttrs> {
     @Column({ type: DataType.INTEGER, autoIncrement: true, unique: true, primaryKey: true})
     id: number
    
     @Column({type: DataType.STRING, unique: true, allowNull: false})
     name: string
    
     @Column({type: DataType.STRING, defaultValue: ""}) 
     description: string
    
     @HasMany(() => Device)
     devices: Device[]
    

    }

  2. Device

      import Group from "../ groups/group.model"
    
    
    
    interface DeviceCreationAttrs {
         model: string
     }
    
     @Table({tableName: "devices"})
     export default class Device extends Model<Device, DeviceCreationAttrs> {
    
     @Column({type: DataType.INTEGER, unique: true, autoIncrement: true, primaryKey: true})
     id: number;
    
     @Column({type: DataType.STRING, unique: true, allowNull: false})
     model: string;
    
     @ForeignKey(() => Group)
     @Column({type: DataType.INTEGER, allowNull: true, defaultValue: null})
     groupId: number
    
     @BelongsTo(() => Group)
     group: Group
    

    }

What I'm ideally trying to do is when in service of group I make a call as

@Injectable()
export default class GroupService {
    constructor(@InjectModel(Group) private groupRepository: typeof Group) {}

    async getAll() {
        const all = await this.groupRepository.findAll()
        return all
    }
}

I should receive array of groups WHERE every object has a keys name, description AND populated devices as ->

[{"id" : 1,
 "name": "Tablets",
 "description": "Elect devices",
 "devices": [{ "id" : 1, "name":"Ipad"}]
}]
0 Answers
Related