如何在 GraphQL 中搜索字符串值 [英] How to search string values in GraphQL
问题描述
如何在类似于 SQL 的 like
运算符的庄园中使用 GraphQL 进行查询?
How do you query using GraphQL in a manor similar to SQL's like
operator?
示例:哪些用户的名字以 jason
开头?
Example: What users have a first name starting with jason
?
select * from users where first_name like "jason%"
推荐答案
简短的回答是:你不需要.
The short answer is: you don't.
更长的答案是您必须自己编写该代码.GraphQL 不像 SQL 那样是一种数据库查询语言,它是一种应用程序查询语言.这意味着 GraphQL 不会让您开箱即用地编写任意查询.它将仅支持您的 GraphQL 架构中定义的查询类型.
The longer answer is that you have to write that code yourself. GraphQL isn't a database query language like SQL, it's an application query language. What that means is that GraphQL won't let you write arbitrary queries out of the box. It will only support the types of queries defined in your GraphQL schema.
如果您希望能够编写包含 like
的查询,您必须
If you want to be able to write a query that contains like
, you have to
a) 在模式中声明,并且b) 编写一个解析函数来获取数据
a) declare that in the schema, and b) write a resolve function that fetches the data
例如,您可以拥有以下架构:
For example, you could have this schema:
type Query {
users(firstName: String!): [User]
}
type User {
firstName: String
lastName: String
}
您必须为 users
字段定义以下解析函数:
You would have to define the following resolve function for the users
field:
{
Query: {
users(root, args){
return sql.raw('SELECT * FROM `users` WHERE `firstName` LIKE ?', args.firstName);
}
}
}
最后编写此查询以获取符合您搜索条件的所有用户的 firstName 和 lastName 列表:
And finally write this query to get a list of firstName and lastName of all the users that match your search criteria:
{
users(firstName: 'jason%'){
firstName
lastName
}
}
这是我不久前写的一篇文章,阐明了有关 GraphQL 的一些概念:https://medium.com/apollo-stack/how-do-i-graphql-2fcabfc94a01
Here's a post I wrote a while ago that clarifies some of the concepts around GraphQL: https://medium.com/apollo-stack/how-do-i-graphql-2fcabfc94a01
这里有一篇文章解释了 GraphQL 模式和解析函数之间的相互作用:https:///medium.com/apollo-stack/graphql-explained-5844742f195e
And here's a post that explains the interplay between GraphQL schemas and resolve functions: https://medium.com/apollo-stack/graphql-explained-5844742f195e
这篇关于如何在 GraphQL 中搜索字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!