使用关联

时间:2017-11-18 14:29:41

标签: mysql node.js database sequelize.js

我目前的模特:

let Book = sequelize.define('book', {
  title: Sequelize.STRING,
  author: Sequelize.STRING,
  ...
});

let Recommendation = sequelize.define('recommendations', {
  reasoning: Sequelize.STRING,
  rating: Sequelize.FLOAT,
});

Book.belongsToMany(Recommendation, {through: 'bookrecommendation'});
Recommendation.belongsToMany(Book, {through: 'bookrecommendation'});

当执行方法addRecommendation下面的代码添加建议书时我得到一个错误错误:无效值[object Promise]

Book.findOrCreate({
  where: { id: '1' }, defaults: {
    author: 'test',
    title: 'test'
  }
})
.spread(function (b, createdBook) {
const rec = Recommendation.create(
  {
    reasoning: 'test',
    rating: 1
  });
  b.addRecommendation(rec).then((result) => {

  }, (error) => {
    console.log(error);
  })
}

1 个答案:

答案 0 :(得分:5)

这里的问题是rec是一个承诺。 这应该解决问题

Book.findOrCreate({ where: { id: '1' }, defaults: {
  author: 'test',
  title: 'test'
}}).spread(function (b, createdBook) {
Recommendation.create({
 reasoning: 'test',
 rating: 1
}).then((rec) => {
  b.addRecommendation(rec).then((result) => {}, (error) => {
    console.log(error);
   })
})