【问题标题】:Delete an item from Database using Typeorm in NestJs在 NestJs 中使用 Typeorm 从数据库中删除一个项目
【发布时间】:2021-05-03 11:53:58
【问题描述】:

我有Users 实体:
id|姓名|年龄|图片
1 |约翰 | 4 | {123.jpg,258.png}
我想从images 列中删除一张图片。根据typeorm 文档,我可以使用:

import {getConnection} from "typeorm";

await getConnection()
    .createQueryBuilder()
    .delete()
    .from(Users)
    .where("id = :id", { id: 1 })
    .execute();

如果使用它,我将删除整个实体,但我只需从 images 列中删除 123.jpg

问题:如何从images 列中删除123.jpg 图像?
注意:我使用 NestJs 和 ProgresQl


用户实体:

@Entity()
export class Users {
    @PrimaryGeneratedColumn()
    id: number;
    
    ...

    @Column("text",{nullable: true, array: true})
    images: string[];
}

【问题讨论】:

  • @AnushKamble,你知道解决办法吗?
  • images 只是 User 实体中的一个 colmun 吗?请分享用户实体
  • @Youba,我更新了。实际上,图像只是一列。有解决办法吗?
  • @AnushKamble,你可以添加你的答案
  • 你应该只更新 colmun,在你的情况下你不需要与 delete 做任何事情

标签: node.js nestjs typeorm


【解决方案1】:
await getConnection()
    .createQueryBuilder()
    .update()
    .set({ images: [...valuesWithoutThatImage] })
    .where("id = :id", { id: 1 })
    .execute();

您需要更新该对象并将图像设置为新的所需值,在这种情况下,它应该包含所有没有 123.jpg 的先前图像

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2022-08-17
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多