javascript - TypeORM 在批量保存时抛出重复错误,而不是忽略或更新现有值
问题描述
正如 TypeOrm FrameWork 上记录的那样,Repository.save
应该保存/插入新值并忽略/更新现有的一次,
但是现在我面临一个问题,即它抛出了duplication error
现有值并停止了整个插入!(我有一个独特的专栏叫key
)
我的实体:
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinColumn, PrimaryColumn } from 'typeorm';
import { Source } from '../sources/source.entity';
@Entity({ name: 'articles' })
export class Article {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({
nullable: true
})
image: string | null;
@Column({
type: "text",
})
url: string;
@Column({
type: "varchar",
unique: true
})
key: string;
@Column({
type: 'datetime',
nullable: true
})
date: Date | null;
@ManyToOne(type => Source, source => source.articles, {eager: true})
@JoinColumn({name: 'source'})
source: Source;
@Column({
type: `text`,
nullable: true
})
description: string | null
}
我的服务:
constructor(
@InjectRepository(Article) private readonly articleRepository: Repository<Article>,
private readonly articlesScraper: BlogScraperService
) {
}
async clonningFromScraper() {
let articles = await this.articlesScraper.articles('1');
articles = articles.map(article => ({ ...article, key: decodeURIComponent(article.url).substring(0, 255) }));
return this.articleRepository
.save(articles);
}
解决方案
我最终使用以下方法通过 RAW SQL 查询解决了这个问题
return this.articleRepository.query(
"INSERT IGNORE INTO articles ( title, date, url, image, source, description, _key ) VALUES ?", [querableArticles]);
推荐阅读
- azure-data-explorer - Partition an unpartitioned table in ADX
- python - 如何提取文件中的句子?
- javascript - JS/React useState 值在函数调用之前没有更新?
- reactjs - 获取对 antd 时间选择器的引用并将其值存储到状态变量
- azure - 如何使用 powerShell 在 Azure 密钥库机密中存储 json 文件内容(密钥)?
- angular - 如何构建旧版本的 Grunt Angular 项目
- file - 抢占式调度会影响移动文件的速度吗?
- powershell - 当我尝试使用多个 allowedMemberTypes 创建应用角色时,它会引发错误
- java - Firebase recyclerview 活动中的原生广告
- mercurial - 有没有办法在 JetBrains IDE 中查看我的分支中的所有更改?