I've read documention typeorm, but un didn't find the solution of my problem. Neither in the forum, somme guys describe suquery, but it's not works with leftJoinAndSelect. If someone can help thanks a lot I've Article entity
@Entity('article')
export class Article extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({type: "longtext"})
content: string;
@Column({ default: false })
is_published: boolean;
@CreateDateColumn({ type: "timestamp", default: () => 'CURRENT_TIMESTAMP' })
createDateTime: Date;
@ManyToOne(type => User, user => user.articles)
user:User;
}
and User entity
@Entity()
export class User extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
@Column({ default: true })
isActive: boolean;
@Column({default: 'contrinutor'})
role: string
@OneToMany(()=> Article, article => article.user)
articles: Article[];
}
I want to get one article and join the user associate to the article, BUT only retrieve data for the article and the username , NOT all info data.
Currently i 've tried this:
const article = await this.articleRepository
.createQueryBuilder('article')
.where({id: id})
.leftJoinAndSelect("article.user","user")
.getOne();
And result :
{
"id": 1,
"title": "My super Title",
"content": "My super content",
"is_published": false,
"createDateTime": "2021-01-21T13:37:15.894Z",
"user": {
"id": 1,
"username": "admin",
"password": "admin",
"isActive": true,
"role": "contributor"
}
}
and that i would wish:
{
"id": 1,
"title": "My super Title",
"content": "My super content",
"is_published": false,
"createDateTime": "2021-01-21T13:37:15.894Z",
"user": {
"username": "admin",
"role": "contrinutor"
}
}
Thanks for help 😁
You can achieve the result wanted by using select
,leftJoin
and AddSelect
:
const article = await this.articleRepository
.createQueryBuilder('article')
.where({id: id})
.leftJoin("article.user","user")
.select(['article'])
.addSelect(['user.username','user.role'])
.getOne();