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

Sequelize.js结合Faker生成种子数据:department_uid基于department_type赋值问题

问题根因

现有代码的核心问题是每次调用deptTypes(items)都会重新随机生成一次部门类型:department_type字段调用一次得到值A,后面department_uid的判断逻辑里每一层三元判断又会重新调用一次deptTypes,多次生成的部门类型完全独立,自然无法对应。


修复方案

推荐使用映射表+单次存值的方案实现,既保证关联匹配,又提升可维护性:

function deptTypes(items) { 
  return items[Math.floor(Math.random()*items.length)]; 
}
const items = ["a", "b","c","d","e","f"]; 
// 提前做部门类型和对应ID列表的映射,替换冗长的嵌套三元判断
const deptListMap = {
  a: alist,
  b: blist,
  c: clist,
  d: dlist,
  e: elist,
  f: flist
}
await queryInterface.bulkInsert('reviews', [...Array(50)].map(() => {
  // 单条数据仅生成一次随机部门类型,后续复用该值保证关联一致
  const currentDeptType = deptTypes(items)
  const targetDeptList = deptListMap[currentDeptType]
  return {
    user_id: users[Math.floor(Math.random()*users.length)].id, 
    title: faker.name.title(), 
    review: faker.lorem.sentences(6), 
    rating: Math.round(Math.random()*5),
    department_type: currentDeptType, 
    department_uid: targetDeptList[Math.floor(Math.random()*targetDeptList.length)].id,
    created_at: new Date(),
    updated_at: new Date()
  }
}), {});

内容的提问来源于stack exchange,提问作者Aravind Kethireddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 22:15:03