简体   繁体   中英

How do I add custom queries in GraphQL using Strapi?

I'm using graphQL to query a MongoDB database in React, using Strapi as my CMS. I'm using Apollo to handle the GraphQL queries. I'm able to get my objects by passing an ID argument, but I want to be able to pass different arguments like a name.

This works:

{
  course(id: "5eb4821d20c80654609a2e0c") {            
    name
    description
    modules {
       title
    } 
  }
}

This doesn't work, giving the error "Unknown argument \"name\" on field \"course\" of type \"Query\"

{
  course(name: "course1") {            
    name
    description
    modules {
       title
    } 
  }
}

From what I've read, I need to define a custom query, but I'm not sure how to do this.

The model for Course looks like this currently:

  "kind": "collectionType",
  "collectionName": "courses",
  "info": {
    "name": "Course"
  },
  "options": {
    "increments": true,
    "timestamps": true
  },
  "attributes": {
    "name": {
      "type": "string",
      "unique": true
    },
    "description": {
      "type": "richtext"
    },
    "banner": {
      "collection": "file",
      "via": "related",
      "allowedTypes": [
        "images",
        "files",
        "videos"
      ],
      "plugin": "upload",
      "required": false
    },
    "published": {
      "type": "date"
    },
    "modules": {
      "collection": "module"
    },
    "title": {
      "type": "string"
    }
  }
}

and the Any help would be appreciated.

Referring to Strapi GraphQL Query API

You can use where with the query courses to filter your fields. You will get a list of courses instead of one course

This should work:

{
  courses(where: { name: "course1" }) {
    name
    description
    modules {
       title
    } 
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM