使用AWS Amplify DataStore查询时能否实现关联表join查询?
可以实现完全相同的关联查询效果,AWS Amplify DataStore原生支持一对多关联的自动查询,不需要手动处理外键逻辑,离线状态下也可以正常使用。
实现方法
你可以直接通过访问模型的关联属性获取关联数据,示例代码如下:
import { DataStore } from 'aws-amplify/datastore'; import { Hospitals } from './models'; // 替换为你的模型文件实际路径 async function fetchHospitalsWithDoctors() { // 查询所有医院数据 const hospitalList = await DataStore.query(Hospitals); // 遍历获取每家医院对应的医生数据,DataStore会自动处理关联查询逻辑 for (const hospital of hospitalList) { // 访问关联属性Doctors即可获取当前医院对应的所有医生 const doctorList = await hospital.Doctors; console.log(`医院 ${hospital.name} 的医生名单:`, doctorList.map(item => item.firstName)); } }
可选优化:预加载关联数据
如果你使用的是Amplify V6及以上版本,可以通过includes参数实现关联数据的预加载,避免遍历过程中多次触发异步查询,性能更优:
import { DataStore } from 'aws-amplify/datastore'; import { Hospitals } from './models'; async function fetchHospitalsWithDoctors() { // 查询医院时指定预加载Doctors关联数据 const hospitalList = await DataStore.query(Hospitals, undefined, { includes: [hospital => hospital.Doctors] }); // 无需额外await,直接访问已加载完成的医生列表 hospitalList.forEach(hospital => { console.log(`医院 ${hospital.name} 的医生名单:`, hospital.Doctors.map(item => item.firstName)); }); }
说明
以上查询逻辑在在线、离线场景下均可正常运行,DataStore会自动将云端的关联关系同步到本地存储,查询时直接读取本地数据即可返回和你提供的GraphQL语句完全一致的结果。
内容的提问来源于stack exchange,提问作者GNG
相关产品推荐
相关产品推荐

