AWS Amplify GraphQL如何查询student关联为空的DriveTime记录
解决方案
核心优化思路:直接过滤关联外键字段
Amplify 的 @model 指令为 @connection 关联自动生成了隐藏的外键字段,你的 DriveTime 表中会存在一个默认名为 studentID 的字段,当 student 关联为空时,该字段值为 null,你可以直接在 GraphQL 查询的过滤条件中对该字段做判断,无需在 Lambda 中二次筛选。
你之前无法直接过滤
student关联为空的记录,是因为关联字段是 GraphQL 解析层动态关联查询的,底层 DynamoDB 的单表查询无法直接跨表过滤,而外键studentID是DriveTime表自身的字段,可以直接作为过滤条件。
改造后的查询代码
const listDrives = `query ListDrives($limit: Int, $nextToken: String, $currentDate: AWSDateTime!) { listDriveTimes( limit: $limit, nextToken: $nextToken, filter: { and: [ {openRegistration: {le: $currentDate}}, {closeRegistration: {ge: $currentDate}}, {studentID: {null: true}} ] } ) { items { id start end openRegistration closeRegistration instructor { firstName lastName } } nextToken } }` // 调用查询时传入变量即可 const variables = { limit: limit, nextToken: nextToken, currentDate: new Date().toISOString() }
优化说明
- 避免直接在查询字符串中拼接日期参数,改用 GraphQL 变量传递,既可以避免格式错误,也能防范注入风险
- 过滤后查询返回的结果已经是符合要求的可用练车时段,直接映射为
AvailableDriveTime结构返回即可,无需额外过滤逻辑 - 如果你自定义了
@connection的外键字段名,将过滤条件中的studentID替换为你自定义的字段名即可
内容的提问来源于stack exchange,提问作者Austin Robinson
相关产品推荐
相关产品推荐

