首页 > 解决方案 > aexmachina/factory-girl(节点)无法将工厂与非持久模型关联

问题描述

我正在尝试将工厂模型与非持久模型相关联,但出现错误:

     TypeError: model.get is not a function
      at SequelizeAdapter.get (node_modules/src/adapters/DefaultAdapter.js:13:18)
      at AssocAttrs.get [as getAttribute] (node_modules/src/generators/Generator.js:15:46)
      at AssocAttrs.getAttribute (node_modules/src/generators/AssocAttrs.js:7:23)
      at tryCatch (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
      at Generator.invoke [as _invoke] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
      at step (node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
      at /Users/daniel.pan/Documents/projects/BudgetApp/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13

这是我拥有的工厂:

import models from '../../models'
import faker from 'faker/locale/en'

export default factory.define('Expense', models.Expense, {
  id: factory.seq('id'),
  value: faker.finance.amount(0, 200),
  note: faker.lorem.sentence(),
  categoryId: factory.assocAttrs('Category', 'id'),
  userId: factory.assocAttrs('User', 'id')
})

我正在尝试将“费用”与“类别”和“用户”相关联。我可以只使用“assoc”并且它可以工作,但这适用于我不想要的持久模型。文档说要使用“assocAttrs”来嵌入未持久化的模型,但是我总是遇到类型错误。我不知道如何进行。

标签: sequelize.jsfactory-bot

解决方案


这已经很晚了,但是将代码行更改如下categoryId

categoryId: factory.assocAttrs('Category', 'id'),

至:

categoryId: factory.assocAttrs('Category'),

调用时应该会产生 JSON 输出:

factory.build('Expense').then(x => console.log(x)). 

您会注意到您的categoryId属性将包含一个 JSON 对象,该对象将包含初始化为您定义它们的属性。那是Expense.category = {propA: 'whatever you've defined', probB: 'etc...', categoryId: '123-213-123'}

为确保该Expense.categoryId属性仅设置为categoryId上述 JSON 对象中的 ,您需要将我上面提到的代码行更改为:

categoryId: factory.assocAttrs('Category')().then(y => y.categoryId)

推荐阅读