返回
Featured image of post TypeORM - Repository

TypeORM - Repository

Repository 其操作僅限於具體實體

20220930-備註更新 此篇文章為 0.2.x


與Table綁定

import {getRepository} from "typeorm";
import {User} from "./entity/User";

const userRepository = getRepository(User);

Repository.find()其中一種從資料庫取得資料的方式。

查詢 .find()

// 使用方式
userRepository.find();
// TypeScript 使用講解
.find(options?: FindManyOptions<Entity>): Promise<Entity[]>;
// FindManyOptions 包括的相對應參數
{
    // 指定應檢索哪些列。
    select?: (keyof Entity)[];
    // 應該應用於匹配實體的簡單條件。
    where?: FindConditions<Entity>[] | FindConditions<Entity> | ObjectLiteral | string;
    // 指示應加載實體的哪些關係(簡化的 join 和 leftJoinAndSelec)。
    relations?: string[];
    // 指定應加載的關係。
    join?: {
            // 要 Join 的 Table別名
            alias: string;
            // Array of columns to LEFT JOIN.
            leftJoinAndSelect?: {
                [key: string]: string;
            };
            // Array of columns to INNER JOIN.
            innerJoinAndSelect?: {
                [key: string]: string;
            };
            // Array of columns to LEFT JOIN.
            leftJoin?: {
                [key: string]: string;
            };
            // Array of columns to INNER JOIN.
            innerJoin?: {
                [key: string]: string;
            };
        };
    // Order,應在其中訂購實體。
    order?: {
        [P in keyof Entity]?: "ASC" | "DESC" | 1 | -1;
    };
    // 啟用或禁用查詢結果緩存。
    cache?: boolean | number | {
        id: any;
        milliseconds: number;
    };
    // 指示應使用哪種鎖定模式。
    lock?: {
        mode: "optimistic";
        version: number | Date;
    } | {
        mode: "pessimistic_read" | "pessimistic_write" | "dirty_read" | "pessimistic_partial_write" | "pessimistic_write_or_fail";
    };
    // 指示是否應將軟刪除的行包括在實體結果中。
    withDeleted?: boolean;
    // 如果設置為true,則將加載實體的所有關係ID並將其映射到關係值(而不是關係對象)。
    // 如果給出了字符串數組,則僅加載給定屬性的關係ID。
    loadRelationIds?: boolean | {
        relations?: string[];
        disableMixedMap?: boolean;
    };
    // 指示是否應加載渴望的關係。
    // 默認情況下,使用查找方法時將加載它們。
    loadEagerRelations?: boolean;
    // 如果將其設置為true,則將在事務中執行“ find”方法中的SELECT查詢。
    transaction?: boolean;
    // 偏移量(分頁),應從實體那裡獲取。
    skip?: number;
    // 限制(分頁)-應採用最大實體數。
    take?: number;
}

Example

userRepository.find({
    select: ["firstName", "lastName"],
    relations: ["profile", "photos", "videos"],
    where: {
        firstName: "Timber",
        lastName: "Saw"
    },
    order: {
        name: "ASC",
        id: "DESC"
    },
    skip: 5,
    take: 10,
    cache: false
});

WHRER進階查詢功能

  • Not
await connection.getRepository(Post).find({title: Not("About #1")})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" != 'About #1'
 */
  • LessThan
await connection.getRepository(Post).find({likes: LessThan(10)})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "likes" < 10
 */
  • LessThanOrEqual
await connection.getRepository(Post).find({likes: LessThanOrEqual(10)})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "likes" <= 10
 */
  • MoreThan
await connection.getRepository(Post).find({likes: MoreThan(10)})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "likes" > 10
 */
  • MoreThanOrEqual
await connection.getRepository(Post).find({likes: MoreThanOrEqual(10)})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "likes" >= 10
 */
  • Equal
await connection.getRepository(Post).find({title: Equal("About #2")})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" = 'About #2'
 */
  • Like
await connection.getRepository(Post).find({title: Like("%out #%")})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" LIKE '%out #%'
 */
  • ILike
await connection.getRepository(Post).find({title: ILike("%out #%")})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" ILIKE '%out #%'
 */
  • Between
await connection.getRepository(Post).find({likes: Between(1, 10)})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "likes" BETWEEN 1 AND 10
 */
  • In
await connection.getRepository(Post).find({title: In(["About #2", "About #3"])})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" IN ('About #2','About #3')
 */
  • Any
await connection.getRepository(Post).find({title: Any(["About #2", "About #3"])})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" = ANY(['About #2','About #3'])
 */
  • IsNull
await connection.getRepository(Post).find({title: IsNull()})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "title" IS NULL
 */
  • Raw
await connection.getRepository(Post).find({
    currentDate: Raw(alias =>`${alias} > ':date'`, { date: "2020-10-06" })
})

/**
 * MySQL Query
 * SELECT * FROM "post" WHERE "currentDate" > '2020-10-06'
 */

新增 .save()

const userRepository = getRepository(User);
user = { firstName: "Phantom", lastName: "Lancer" };
await userRepository.save(user);

更新 .update()

const userRepository = getRepository(User);
user = { firstName: "Timber", lastName: "Saw" };
await userRepository.update({ id: 1 }, user);

刪除 remove()/.delete()

兩者皆刪除,有一點差別

// remove()
let userRepository = connection.getRepository(User)
let user = userRepository.create({name:'測試員'})
await userRepository.save(user)
console.log(user)         // User {name: '測試員'}
let result = await userRepository.remove(user)
console.log(user)         // User {name: '測試員'}
console.log(result)       // User {name: '測試員'}
// delete()
let userRepository = connection.getRepository(User)
let user = userRepository.create({name:'測試員'})
await userRepository.save(user)
console.log(user)         // User {name: '測試員'}
let result = await userRepository.delete(user)
console.log(user)         // User {name: '測試員'}
console.log(result)       // undefinded
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus