• 使用 Repositories

    使用 Repositories

    现在让我们重构之前的代码,并使用Repository而不是EntityManager。每个实体都有自己的存储库,可以处理其实体的所有操作。当你经常处理实体时,Repositories 比 EntityManagers 更方便使用:

    1. import { createConnection } from "typeorm";
    2. import { Photo } from "./entity/Photo";
    3. createConnection(/*...*/)
    4. .then(async connection => {
    5. let photo = new Photo();
    6. photo.name = "Me and Bears";
    7. photo.description = "I am near polar bears";
    8. photo.filename = "photo-with-bears.jpg";
    9. photo.views = 1;
    10. photo.isPublished = true;
    11. let photoRepository = connection.getRepository(Photo);
    12. await photoRepository.save(photo);
    13. console.log("Photo has been saved");
    14. let savedPhotos = await photoRepository.find();
    15. console.log("All photos from the db: ", savedPhotos);
    16. })
    17. .catch(error => console.log(error));

    了解更多有关 Repository 的信息。