You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WatermelonDB如何查询包含关联账户信息的交易记录

获取WatermelonDB中交易记录关联的完整账户信息

核心方案:使用with()预加载关联数据

WatermelonDB默认对关联关系采用懒加载,要直接获取完整关联实体,需在查询时通过.with()方法显式指定预加载的关联字段。

步骤说明

  1. 确认关联配置正确性
    你的模型关联配置已经正确:

    • Transaction模型通过@relation('accounts', 'account_id') account定义了与Account的belongs_to关联
    • Account模型通过static associations定义了has_many关联,且foreignKey匹配account_id
  2. 编写查询代码
    执行查询时,调用.with('account')来预加载每个交易对应的完整Account记录:

    // 假设你已经初始化了database实例
    const transactionsWithAccounts = await database
      .get('transactions')
      .query()
      .with('account') // 预加载关联的account数据
      .fetch();
    
  3. 访问关联数据
    此时返回的每个transaction对象的account属性就是完整的Account实体,可直接访问其字段:

    transactionsWithAccounts.forEach(transaction => {
      console.log(`交易ID: ${transaction.id}`);
      console.log(`金额: ${transaction.amount}`);
      console.log(`关联账户名称: ${transaction.account.title}`);
      console.log(`账户描述: ${transaction.account.description}`);
    });
    

扩展:加载多个关联

如果需要同时加载transactionCategory关联,可链式调用多个.with():

const transactionsWithRelations = await database
  .get('transactions')
  .query()
  .with('account')
  .with('transactionCategory')
  .fetch();

内容的提问来源于stack exchange,提问作者raghav nagpure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:27:27