如何在Hasura Data API中编写接收用户输入的查询及PostgreSQL语句
Great question! Let's walk through how to adjust your existing Hasura request to return results based on user-provided movie names, plus break down the equivalent PostgreSQL logic behind it.
1. Updated Hasura Data API Request Payload
Your current payload fetches all overview entries from the collect table—we just need to add a where clause to narrow results to the user's chosen movie. Here's the modified payload with a hardcoded example (we'll cover dynamic user input next):
{ "type": "select", "args": { "table": "collect", "columns": ["overview"], "where": { "movie_name": { "_eq": "用户输入的名称" } } } }
- The
_eqoperator is Hasura's way of specifying an exact match. If you need partial matches (like searching for movies containing a keyword), you can use_likeinstead (e.g.,{"_like": "%star%"}for movies with "star" in the name).
Handling Dynamic User Input
If you're pulling the movie name from a user input (like a form field), you'll inject that value into the payload dynamically. For example, in a JavaScript frontend:
// Get user input from a form field const userMovieName = document.querySelector('#movie-search').value; // Build the request payload with the user's input const requestPayload = { "type": "select", "args": { "table": "collect", "columns": ["overview"], "where": { "movie_name": { "_eq": userMovieName } } } };
Don't forget to send this with your existing Content-Type: application/json header—Hasura requires this to parse the payload correctly.
2. Equivalent PostgreSQL SQL Statement
The Hasura query above directly maps to the PostgreSQL query you described:
SELECT overview FROM collect WHERE movie_name = '用户输入的名称';
Critical Note: Never concatenate user input directly into SQL strings—it exposes you to SQL injection attacks. Always use parameterized queries. In PostgreSQL, that looks like:
SELECT overview FROM collect WHERE movie_name = $1;
Hasura handles this parameterization automatically when you use the Data API, so you don't have to worry about sanitizing input manually here.
3. Full Request Example (with curl)
To test this, you can send the request via curl (replace https://your-hasura-endpoint/v1/graphql with your actual Hasura instance URL):
curl -X POST https://your-hasura-endpoint/v1/graphql \ -H "Content-Type: application/json" \ -d '{ "type": "select", "args": { "table": "collect", "columns": ["overview"], "where": { "movie_name": { "_eq": "你的电影名称" } } } }'
Sample Response
If there's a matching movie, you'll get a JSON array with the result:
[{"overview": "This is a great movie about space exploration..."}]
内容的提问来源于stack exchange,提问作者Vandana

