代码之家  ›  专栏  ›  技术社区  ›  pirmax

TypeORM-find all方法查找用户的所有文章

  •  0
  • pirmax  · 技术社区  · 8 年前

    我想从 包裹。

    后遗症 ,我有:

    async findAllByUser(userUuid: string, findOptions: object): Promise<Article[]> {
        return await Article.findAll<Article>({
            include: [{
                model: User,
                where: {
                    uuid: userUuid
                }
            }]
        });
    }
    

    类型

    1 回复  |  直到 8 年前
        1
  •  2
  •   hgiasac    8 年前

    如果在模型中定义了关系,则可以加入

    export class Article {
        /// ... other columns
    
        @ManyToOne(type => Author, author => author.articles)
        author: Author;
    }
    

    有两种查询方式: find* QueryBuilder

    // find*
    
    createConnection(/*...*/).then(async connection => {
    
        /*...*/
        let articleRepository = connection.getRepository(Article);
        let articles = await articleRepository.find({ relations: ["author"] });
    
    }).catch(error => console.log(error));
    
    // Query Builder
    const articles = await connection
        .getRepository(Article)
        .createQueryBuilder("article") 
        .leftJoinAndSelect("article.author", "user")
        .getMany();
    

    你可以阅读 documentation 更多细节