本文共 2625 字,大约阅读时间需要 8 分钟。
typeorm删除一个实体有两类方法:
delete、deleteById
remove、removeById、removeByIds
其中remove能够触发subscriber、entity listener。而delete方法不能触发已经讨论过了,这类似于save与insert、update的关系
下面在使用上也做一些区分:
1.正常删除,删除已存在实体
remove:
import { createConnection,Repository } from 'typeorm'import { User } from './User'createConnection({ name:'test', type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: '123456', database: "test", synchronize:true, dropSchema:true, charset:'UTF8', entities: [ User ]}).then(async (connection)=>{ let userRepository = connection.getRepository(User) let user = userRepository.create({id:1,name:'张三'}) await userRepository.save(user) console.log(user) let result = await userRepository.remove(user) console.log(result==user) console.log(user) console.log(result)})
输出:
User { id: 1, name: '张三' }trueUser { id: undefined, name: '张三' }User { id: undefined, name: '张三' }
remove返回的结果与被操作的实体为一个实体,经过remove,id变为undefined
removeById、removeByIds直接操作id,返回undefineddelete:
then(async (connection)=>{ let userRepository = connection.getRepository(User) let user = userRepository.create({id:1,name:'张三'}) await userRepository.save(user) console.log(user) let result = await userRepository.delete(user) console.log(user) console.log(result)})
输出:
User { id: 1, name: '张三' }User { id: 1, name: '张三' }undefined
可见delete不改变被操作实体,且返回undefined
deleteById:与delete类似
可见delete、deleteById、removeById、removeByIds这几个方法的操作效果以及返回值比较类似
2.删除不存在实体
remove:
then(async (connection)=>{ let userRepository = connection.getRepository(User) let user = userRepository.create({id:1,name:'张三'}) await userRepository.save(user) let result = await userRepository.remove({id:2,name:'李四'}) console.log(result)})
输出:
UnhandledPromiseRejectionWarning: Error: Database entity is not set for the given subject.
可见,remove在删除之前应该对实体有一个预加载的过程,找不到实体就会报错
removeById、removeByIds行为则不同,不报错,直接返回undefined,说明其内部处理应该与remove不同
注意:remove方法不能对简单对象进行操作,必须是一个完整的User对象,也就是id、name属性都必须存在,不能只删除指定id的对象
delete:
then(async (connection)=>{ let userRepository = connection.getRepository(User) let user = userRepository.create({id:1,name:'张三'}) await userRepository.save(user) let result = await userRepository.delete({id:2}) console.log(result)})
输出:undefined
使用delete删除,不报错直接返回undefined
deleteById:与delete类似
可见,removeById、removeByIds、deleteById、delete这四个方法操作效果是类似的,而删除不存在数据不报错与更新不存在数据不报错本身就是数据库特性:
delete from user where id=2;
Query OK, 0 rows affected (0.00 sec)
可见,数据库中删除不存在数据时,影响行数为0
delete from user where id=1;
Query OK, 1 row affected (0.00 sec)
当删除存在数据时,影响行数为1
转载地址:https://blog.csdn.net/qq_27868061/article/details/79315985 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!