正如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]);

10-05 21:44