使用Bookshelf fetchAll()关联多表获取报告数组报错求助
这问题很典型——你混淆了单个Model和Collection对象的方法差异!.fetch()返回的是单个报告Model,所以能直接调用.related();但.fetchAll()返回的是报告集合(Collection),它本身没有.related()方法,得遍历集合里的每个单个Model来处理关联数据。
问题原因拆解
你当前代码里的report变量是Collection实例,而.related()是Model类的专属方法,直接在Collection上调用自然会报report.related is not a function错误。
修改后的代码实现
我们需要遍历集合里的每个报告模型,为每个报告单独获取它的关联数据,然后把关联数据合并到该报告的属性中,最终返回包含完整关联数据的报告数组:
exports.getReport = (date) => { return Reports.where(date) .fetchAll({ withRelated: ['feeding', 'comment', 'diapering', 'nap', 'meds', 'playTime', 'supplies'] }) .then(collection => { // 遍历集合中的每个报告模型 return collection.models.map(rep => { // 获取当前报告的基础属性 const reportData = rep.attributes; // 为当前报告单独获取各关联数据并转换为属性数组 const feedingList = rep.related('feeding').map(item => item.attributes); const commentList = rep.related('comment').map(item => item.attributes); const diaperingList = rep.related('diapering').map(item => item.attributes); const napList = rep.related('nap').map(item => item.attributes); const medsList = rep.related('meds').map(item => item.attributes); const playTimeList = rep.related('playTime').map(item => item.attributes); const suppliesList = rep.related('supplies').map(item => item.attributes); // 合并基础数据和关联数据,返回完整的报告对象 return { ...reportData, feeding: feedingList, comment: commentList, diapering: diaperingList, nap: napList, meds: medsList, playTime: playTimeList, supplies: suppliesList }; }); }) .catch(err => { console.error('获取报告失败:', err); throw err; // 抛出错误让调用方可以捕获并处理 }); };
额外优化点
- 你原来代码里有个顺序错误:
return reports写在了const reports = ...之前,这会导致未定义错误,上面的代码已经修正了这个问题。 - 现在每个报告对象都包含自己的关联数据,结构和你最开始定义的
reports.data结构完全匹配,方便后续前端直接使用。 - 错误处理里建议抛出错误,而不是只打印,这样调用这个方法的地方能捕获并处理异常。
内容的提问来源于stack exchange,提问作者Jaime Ivy Arrestinya Pendlebur
相关产品推荐
相关产品推荐

