hasmany in express js不使用sequelize

时间:2017-08-14 11:15:09

标签: express

我创建了模特技能和成员

会员表:

id  username    password    created
1   gagandeep   99703dd91da5b0cabf496d49af0ab03c2dfe7788    2017-08-14 05:59:46

技能表:

id  member_id   skill
1   1   programming
2   1   music

代码:

模型

var Member=Seq.define('members',{}, {});
var Skills=Seq.define('skills',{}, {});
Member.hasMany(Skills,{as: 'skills', through: 'skills', foreignKey:'member_id'});

呼叫:

router.route('/test').get(function(req, resp){
    Member.findAll({include: [{model: Skills}]},{
            raw:true
        }).success(onSuccess).error(onError);

        function onSuccess(data){
            resp.json(data);
        }

        function onError(data){
            resp.json(data);
        }
});

但Node js显示错误如下:

错误:技能与会员无关! at DAOFactory.validateIncludedElement(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ sequelize \ lib \ dao-factory.js:1476:13)at DAOFactory.validateIncludedElements(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ sequelize \ lib \ dao-factory.js:1388:59)在DAOFactory.module.exports.DAOFactory.findAll(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ sequelize \ lib \ dao-factory.js:458: 34)在next_layer处的Object.handle(C:\ Users \ promatics \ Desktop \ netpar \ demo.js:72:9)(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ express \ lib \ router \ route)。 js:103:13)在C:\ Users \ promatics \ Desktop \ netpar \的Route.dispatch(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ express \ lib \ router \ route.js:107:5)在Function.proto.process_params(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ express \ lib \ router \ index.js:251:12)中的node_modules \ express \ lib \ router \ index.js:195:24 next(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ express \ lib \ router \ index.js:189:19)at next(C:\ Users \ promatics \ Desktop \ netpar \ node_modules \ exp RESS \ lib中\路由器\ index.js:166:38)

1 个答案:

答案 0 :(得分:1)

您实际上并不需要through声明。通过联结表在两个表之间建立关联时,只使用through。我在这里会做的就是......

var Member = Seq.define('members', {
  // Some attributes...
});

var Skills = Seq.define('skills', {
  // Some attributes...
});

Member.hasMany(Skills, {
  as: 'skills', 
  // Remove `through`!
  foreignKey: 'member_id'
});

// Want to query for all members with the skills joined?
Member.findAll({
  include: {
    model: Skills,
    as: 'skills'
  }
});

那应该可以得到你想要的结果。每个member对象都会引用一个内部skills键,该键将是与用户关联的一系列技能。

祝你好运:)