Oleg Khalidov
Oleg Khalidov

Reputation: 5268

Strapi: query images

I have a model (Product) that has a list of images. How to fetch the paths to the files?

const data = await Category
      .forge()
      .orderBy('order', 'DESC')
      .fetchAll({
        withRelated: [
          'products',
          'products.images',
        ]
      })

Using the query above I get this 'images' data:

[{
    "id": 6,
    "upload_file_id": 6,
    "related_id": 2,
    "related_type": "products",
    "field": "images"
}]

Strapi v3.0.0-alpha.19, ORM BookshelfJS (afaik)

Upvotes: 1

Views: 2887

Answers (3)

Vivek
Vivek

Reputation: 166

You can query through upload_file model using id for getting the required data.

const Data = await strapi.query('file', 'upload').findOne({id : data.upload_file_id});
    
console.log(Data.url)

Upvotes: 0

James Hooper
James Hooper

Reputation: 2000

You can also fetch the data from Strapi with the upload (media library) API endpoint.

curl http://mystrapidomain.com/upload/files will generate a list of all uploaded assets, plus the auto-generated formats for alternative devices (if enabled). It's an array of image objects, where each object has name, alt text, caption, sizes and formats, and lots of other information.

Upvotes: 1

Oleg Khalidov
Oleg Khalidov

Reputation: 5268

The best approach I could find so far is to address to upload plugin to fetch the data:

for (const category of categories) {
    for (const product of category.products) {
        const files = await strapi.plugins.upload.models.file
            .where('id', 'IN', product.images.map(i => i.upload_file_id))
            .fetchAll();
        product.images = files.models.map(f => f.attributes)
    }
}

Hope there is a better option to get all the data at once

Upvotes: 2

Related Questions