如何从左联接表中选择数据?

时间:2020-10-15 12:42:20

标签: nestjs typeorm

我有两个实体:“用户”和“设置”表。

@Entity()
export class Users {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;
    
    @Column()
    settingID: number;
}
@Entity()
export class Settings {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;
}

如何从“设置”表中选择数据?

        return this.usersRepository
            .createQueryBuilder("users")
            .select(['users.id', 'users.name', 'settings.name'])
            .leftJoinAndSelect(Settings, 'settings', 'users.settingID = settings.id')
            .getMany();

现在我没有从“设置”表中获取数据,只有用户表。

1 个答案:

答案 0 :(得分:3)

return this.usersRepository
    .createQueryBuilder("users")
    .select(['users.id', 'users.name'])
    .leftJoinAndSelect('users.settings', 'settings', 'users.settingID = settings.id')
    .addSelect(['settings.name', 'settings.prop1', 'settings.prop2'])
    .getMany();

return this.usersRepository
    .createQueryBuilder("users")
    .leftJoinAndSelect('users.settings', 'settings', 'users.settingID = settings.id')
    .select(['users.id', 'users.name', 'settings.name', 'settings.prop1', 'settings.prop2'])
    .getMany();