插入数据
import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Photo } from '../entity/photo'; import { Repository } from 'typeorm'; @Provide() export class PhotoService { @InjectEntityModel(Photo) photoModel: Repository<Photo>; // save async savePhoto() { // create a entity object let photo = new Photo(); photo.name = 'Me and Bears'; photo.description = 'I am near polar bears'; photo.filename = 'photo-with-bears.jpg'; photo.views = 1; photo.isPublished = true; // save entity const photoResult = await this.photoModel.save(photo); // save success console.log('photo id = ', photoResult.id); } }
查询数据
import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Photo } from '../entity/photo'; import { Repository } from 'typeorm'; @Provide() export class PhotoService { @InjectEntityModel(Photo) photoModel: Repository<Photo>; // find async findPhotos() { // find All let allPhotos = await this.photoModel.find({}); console.log("All photos from the db: ", allPhotos); // find first let firstPhoto = await this.photoModel.findOne({ where: { id: 1 } }); console.log("First photo from the db: ", firstPhoto); // find one by name let meAndBearsPhoto = await this.photoModel.findOne({ where: { name: "Me and Bears" } }); console.log("Me and Bears photo from the db: ", meAndBearsPhoto); // find by views let allViewedPhotos = await this.photoModel.find({ where: { views: 1 } }); console.log("All viewed photos: ", allViewedPhotos); let allPublishedPhotos = await this.photoModel.find({ where: { isPublished: true } }); console.log("All published photos: ", allPublishedPhotos); // find and get count let [allPhotos, photosCount] = await this.photoModel.findAndCount({}); console.log("All photos: ", allPhotos); console.log("Photos count: ", photosCount); } }
更新数据库
import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Photo } from '../entity/photo'; import { Repository } from 'typeorm'; @Provide() export class PhotoService { @InjectEntityModel(Photo) photoModel: Repository<Photo>; async updatePhoto() { let photoToUpdate = await this.photoModel.findOne(1); photoToUpdate.name = "Me, my friends and polar bears"; await this.photoModel.save(photoToUpdate); } }
删除数据
import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Photo } from '../entity/photo'; import { Repository } from 'typeorm'; @Provide() export class PhotoService { @InjectEntityModel(Photo) photoModel: Repository<Photo>; async updatePhoto() { /*...*/ let photoToRemove = await this.photoModel.findOne({ where: { id: 1 } }); await photoToRemove.remove(); } }
现在,ID = 1的 Photo 将从数据库中删除。
此外还有软删除的方法。
await this.photoModel.softDelete({ where: { id: 1 } });