Sails.js How to insert data into a join table (Many to Many)

只愿长相守 提交于 2019-12-24 15:42:31

问题


I am having an error inserting data into my join table and I don't know if I'm doing it the right way. Here are my 2 models that have the many to many association.

Commit.js:

module.exports = {
  schema: true,
  attributes: {
    idCommit : {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true,
      unique: true
    },
    revision : {
    type: 'integer',
    required: true
    },
    issues: {
      collection: 'issue',
      via: 'commits',
      dominant: true
    }
  }
};

Issue.js:

module.exports = {
  schema: true,
  attributes: {
    idIssue : {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true,
      unique: true
    },
    description: {
    type: 'string',
    required: true
    },
    commits: {
      collection: 'commit',
      via: 'issues'
    }
  }
};

When I try to insert issues into a commit this way :

Commit.create(commit).exec(function(err,created){
  if (err) {
    console.log(err);
  }
  else { 
    created.issues.add(issues);
    created.save(function(err) {});
  }
});

My commit is created, my issues are created, but there is no link what so ever between them and the join table stays empty. Where did I get it wrong?


回答1:


From your code it looks like your trying to add an array of issues, try doing the association individually, like they do in the Many-to-Many docs

Commit.create(commit).exec(function(err,created){
  if (err) {
    console.log(err);
  }
  else { 

    issues.forEach(function(issue, index){
        created.issues.add(issue);
    })

    created.save(function(err) {});
  }
});


来源:https://stackoverflow.com/questions/29396059/sails-js-how-to-insert-data-into-a-join-table-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!