Brian B.
Brian B.

Reputation: 1

In a GROQ query can you get each asset's data in an array of image references?

I have an array of images in my schema, a gallery. I want to return the image urls for each of the images in the array with my GROQ query.

If I do image{asset->} it works, for a single image.

For an example of the actual query, I'm trying to attempt something like this:

*[_type == 'gallery'] {_id, title, description, images[asset->]} 

I'm using the vision plugin to play with this query. It returns an empty array.

Upvotes: 0

Views: 3835

Answers (2)

Hamza Tasadaq
Hamza Tasadaq

Reputation: 11

My Schema

const product = {
    name: "product",
    title: "Products",
    type: "document",
    fields: [
        {
            name: "name",
            title: "Name",
            type: "string",
        },
        {
            name: "slug",
            title: "Slug",
            type: "slug",
            options: { source: "name" }
        },
        {
            name: "images",
            title: "Images",
            type: "array",
            of: [{
                type: 'image',
                fields: [
                    {
                        name: "alt",
                        title: "Alt",
                        type: "string"
                    },
                ],
                options: { hotspot: true },
            }]
        },
        {
            name: "price",
            title: "Price",
            type: "number"
        },
        {
            name: "description",
            title: "Description",
            type: "array",
            of: [{ type: "block" }]
        }
    ]
};

My Query

  groq`*[_type == "product"]{
            _id,
            _createdAt,
            name,
            "slug": slug.current,
            "images":   images[].asset->url ,
            price,
            description
        }`

Upvotes: -1

knut
knut

Reputation: 391

I believe the correct syntax is:

*[_type == 'gallery']{
    _id, 
    title,
    description,
    images[]{
      asset->{url}
    }
 }

If you want just an array of the URLs directly on the images key:

"images": images[].asset->url

Upvotes: 6

Related Questions