TypeORM 关系查询,只查部分字段该怎么写?
hello, 请问下,我有三个表,collections, users, user_collection, users和 collections是多对多的关系, 根据id查collection,同时查出这个collection的users, 如下
@Entity({name: 'users'})
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column('varchar', { length: 100 })
username: string;
@ManyToMany(type => Collection, collection => collection.users)
@JoinTable({
name: 'user_collection',
joinColumn: {
name: 'user_id',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'collection_id',
referencedColumnName: 'id',
},
})
collections: Collection[];
...
@Entity({name: 'collections'})
export class Collection {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(type => User, user => user.collections)
users: User[];
...
查询代码如下,这样查询,会得到user的所有字段,如果只想查询user的部分字段,如id, username的话,应该怎么写呢?
await this.collectionRepository.findOne({
select: ['id', 'name', 'coverURL', 'announcement', 'allowPost', 'postMustAudit', 'creator'],
where: { id },
relations: [ 'users' ],
});
2 回复
await this.collectionRepository.createQueryBuilder('collection')
.select([
'collection.id',
'collection.name',
'collection.coverURL',
'collection.announcement',
'collection.allowPost',
'collection.postMustAudit',
'collection.creator',
'user.id',
'user.name',
])
.leftJoin('collection.users', 'user')
.where('collection.id = :id', { id })
.getOne();
@huanz 感谢