Strapi delete files related to an entry

Jon*_*nas 9 strapi

I have implemented the functionality to upload files related to an entry.

For example I have a collection type Articles, which has the field photos.

When uploading a file, I can specify the collection, the entry of the collection and the filed to add the media data to.

Now I want to implement the same for deleting a file.

How would I implement this. As far as I know there is no similar method where I delete a media item and it automatically removes the associated entry of my photos field. So I would do it in multiple steps:

  1. Fetch the Articles Entry where I want to remove an item of the photos field.
  2. Articles使用 PUT 请求更新条目,其中我删除了该photos字段的条目。
  3. 使用 DELETE 请求删除关联的上传。

但这是否不允许第 1 组和第 2 组之间出现数据竞争条件?如何确保步骤 2 更新了最新的条目,并且在步骤 1 中获取条目后没有对该条目进行更新?

小智 1

您必须修改该特定 API 的删除服务。

如果要删除关联文件或文件ID之类的,请检查向后端传递一个提示,然后在删除服务运行时检查该“提示”是否存在,如果存在,则删除该文件

const file = await strapi.plugins['upload'].services.upload.fetch({ id });
await strapi.plugins['upload'].services.upload.remove(file);
Run Code Online (Sandbox Code Playgroud)

这是 Strapi 文档中的示例:

async delete(entityId, params) {
  // some logic here
  const result = await super.delete(entityId, params);
  // some more logic

  return result;
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读更多信息: https://docs.strapi.io/dev-docs/backend-customization/services#extending-core-services