简体   繁体   中英

Sequelize.js,How to insert a model with one to many to many relationship

I'am use sequlize.js creat a model with one to many,it can work,but I want to create a model with one to many to many,I don't konw where to start

Now I have defined three model,below is they relationship

  1. Projects
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

There is a object,I want to create through Project Model

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

I try one to many like Office Document, it can work well as follow

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

if I change the code,it work error

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

It's the error stack

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

In fact,I want to code like this,but above code dont work

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

after Travis Haby suggest, I retry

I imitate Sequlize.js Document,change thire relationship define

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' });

the create code

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

or

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

the tow ways only create project, and each way both color and size not created

[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');

According to this part of the sequelize docs you should be able to nest as follows (depending on which version of sequelize you're using):

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

At first glance it looks like you have Projects.Colors and then Projects.Sizes , but I think it should be Colors.Sizes instead because thats the many to many relationship.

Hope that helps!

First, try changing projectColors association to this (assuming you receive models as an argument):

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

Second, try adding to ProjectSizes:

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

NOTE: the model name (that you use after models. ) is the name as defined in the model definition ( Sequelize.define([modelname] ).

Let me know if it helped.

The create should look like this I believe:

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

I try and try again, it work well. thanks @Sagi Rika & @Travis Haby

In fact, it's so simple

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' });
  };

And call create method as follow

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM