Sequelize.js,如何插入具有一对多关系的模型

时间:2019-04-04 03:05:31

标签: javascript sequelize.js

我正在使用sequlize.js创建一个多对多的模型,它可以工作,但是我想创建一个多对多的模型,我不知道从哪里开始

现在我定义了三个模型,下面是它们的关系

  1. 项目
Projects.associate = () => {
    Projects.Colors = Projects.hasMany(ProjectColors, { foreignKey: 'project_id', sourceKey: 'id' });
  };
  1. ProjectColors
ProjectColors.associate = () => {
    Projects.Sizes = ProjectColors.hasMany(ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });
  };
  1. ProjectSizes

有一个对象,我想通过项目模型创建

const project = {
  name: 'xxproject',
  colors:[
    {
      color: 'red',
      sizes:[
        {size: 'L'}
      ]
    },
    {
      color: 'bule',
      sizes:[
        {size: 'L'},
        {size: 'M'}
      ]
    },
  ]
}

我像Office Document一样尝试了很多,它可以很好地工作,如下所示

await Projects.create(project, {
  include: [ Projects.Colors ],
});

如果我更改代码,它将导致工作错误

await Projects.create(project, {
      include: [{
        model: Projects.Colors,
      }],
    });

这是错误堆栈

2019-04-04 10:57:10,074 ERROR 60510 [-/127.0.0.1/-/20ms POST /api/v1/projects] nodejs.TypeError: self._expandAttributes is not a function
    at Function._conformOptions (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:198:12)
    at Function._conformInclude (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:264:12)
    at options.include.options.include.map.include (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:213:59)
    at Array.map (<anonymous>)
    at Function._conformOptions (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:213:39)
    at new Model (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:3070:24)
    at new projects (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/sequelize.js:340:19)
    at Function.build (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:1966:12)
    at Function.create (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:2017:17)
    at ProjectController.create (/Users/jaytam/school/garment-production-backend/app/controller/projects.js:42:20)
    at Object.callFn (/Users/jaytam/school/garment-production-backend/node_modules/egg-core/lib/utils/index.js:44:21)
    at Object.classControllerMiddleware (/Users/jaytam/school/garment-production-backend/node_modules/egg-core/lib/loader/mixin/controller.js:87:20)
    at Object.callFn (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/utils.js:12:21)
    at wrappedController (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/egg_router.js:322:18)
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:44:32)
    at next (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:45:18)
    at /Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/router.js:190:18
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:44:32)
    at /Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:36:12
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/router.js:195:33)
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/koa-compose/index.js:42:32)
    at /Users/jaytam/school/garment-production-backend/app/middleware/handleGetInt.js:22:11

实际上,我想这样编码,但是上面的代码不起作用

await Projects.create(project, {
      include: [{
        model: Projects.Colors,
        include: [{
          model: Projects.Sizes,
        }],
      }],
    });

在特拉维斯·哈比建议之后,我重试

我模仿Sequlize.js文档,更改关系定义

Projects.Colors = app.model.ProjectColors.belongsTo(Projects, { foreignKey: 'project_id', targetKey: 'id' });
app.model.ProjectColors.Sizes = app.model.ProjectColors.hasMany(app.model.ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });

创建代码

await Projects.create(project, {
      association: Projects.Colors,
      include: [ ProjectColors.Sizes ],
});

    await Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [{
          association: ProjectColors.Sizes,
        }],
      }],
    })

两种方式只能创建项目,而每种方式都不能创建颜色和尺寸

[2019-04-04 14:22:15.564] [cfork:master:60831] worker:60969 exit (code: 0, exitedAfterDisconnect: true, state: dead, isDead: true, isExpected: true, worker.disableRefork: false)
{ name: 'sadqw',
  cycle: 230,
  fund: 1230123,
  manage_by: 'dsa',
  project_colors: [ { color: 'asd', imageUrl: '', project_sizes: [Array] } ],
  status: '0' }
2019-04-04 14:26:24,276 INFO 60980 [egg-sequelize](1ms) Executed (default): INSERT INTO `projects` (`id`,`name`,`cycle`,`fund`,`manage_by`,`created_at`,`updated_at`,`status`) VALUES (DEFAULT,'sadqw',230,1230123,'dsa','2019-04-04 06:26:24','2019-04-04 06:26:24','0');

3 个答案:

答案 0 :(得分:0)

根据this part of the sequelize docs,您应该能够按照以下方式嵌套(取决于您使用的sequelize的版本):

return Projects.create(project, {
  include: [{
    association: Projects.Colors,
    include: [ Colors.Sizes ]
  }]
});

乍看之下,您似乎拥有Projects.Colors,然后是Projects.Sizes,但我认为应该是Colors.Sizes,因为那是多对多关系。

希望有帮助!

答案 1 :(得分:0)

首先,尝试将projectColors关联更改为此(假设您收到models作为参数):

ProjectColors.associate = () => {
    ProjectColors.Sizes = ProjectColors.hasMany(models.project_size, { foreignKey: 'project_color_id', sourceKey: 'id' });
    ProjectColors.Projects = ProjectColors.belongsTo(models.project)
};

第二,尝试添加到ProjectSizes:

ProjectSizes.associate = () => {
    ProjectSizes.Colors = ProjectSizes.belongsTo(models.project_color, { foreignKey: 'project_color_id'});
};

注意:模型名称(您在models.之后使用)是模型定义(Sequelize.define([modelname])中定义的名称。

让我知道是否有帮助。

我相信创建应如下所示:

await Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [ ProjectColors.Sizes ]
      }]
    });

答案 2 :(得分:0)

我尝试再试一次,效果很好。谢谢@Sagi Rika和@Travis Haby

事实上,它是如此简单

Projects.associate = () => {
    Projects.Colors = Projects.hasMany(ProjectColors, { foreignKey: 'project_id', sourceKey: 'id' });
  };
ProjectColors.associate = () => {
    Projects.Sizes = ProjectColors.hasMany(ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });
  };

并按如下所示调用create方法

    Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [{
          association: Projects.Sizes,
        }],
      }],
    })