Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

How can I return an array in GraphQL if I don't know how many there are (PHP, rebing/graphql-laravel)

There is a JSON array:

[{
   "src":{
      "hd":"1.jpeg",
      "small":"2.jpeg"
   }},
{
   "src":{
      "hd":"1.jpeg",
      "small":"2.jpeg"
   }
}]

How do I get the list through GraphQL? I don't know how many elements there are.

I can get a one dimensional array with pictures:

$pictures = new ObjectType(
    [
        'name' => 'pictures',
        'fields' => [
            'small' => [
                'type' => Type::string(),
            ],
            'hd' => [
                'type' => Type::string(),
            ],
        ]
    ]
);

return [
    ......
    'image' => [
    'type' => $pictures,
    'is_relation' => false,
    'resolve' => function ($content) {
        return $content->image[0]; // I return one here, but I need a list
    },
],
......

But how can I get an array of pictures if I don't know how many there are? Maybe one picture, maybe 10. Googled for half a day, found information that GraphQL can return only what is hardcoded... Is it so?

question from:https://stackoverflow.com/questions/65918881/how-can-i-return-an-array-in-graphql-if-i-dont-know-how-many-there-are-php-re

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not necessary to know the number of images.

It seems that you need to define the Type of the field images correctly.

GraphQL know custom types and primitives.

type Image{
  name: String!
  small: String!
}

Image is a custom type, String is a primitive or basic type.

What you are probabably missing is, that you can have a list of a certain type.

I don't know your GQL framework, but here is an example:

Line 23:

Look at Type::listOf()

So, what you will need to do:

  • define an ObjectType for a single Image (your current $images type)
  • And then have a field images in your schema defined as return type list of image

Then you can resolve with return $content->image instead of return $content->image[0]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...