Sequelize关联不与模型定义同步

时间:2019-10-05 01:24:15

标签: javascript node.js sequelize.js sequelize-cli

'use strict';
module.exports = (sequelize, type) => {
  const article_comment = sequelize.define('article_comments', {
    // attributes
    id: {
      type: type.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    positive_rating:{
      type: type.INTEGER,
      allowNull: false
    },
    negative_rating:{
      type: type.INTEGER,
      allowNull: false
    },
    comment:{
      type: type.STRING,
      allowNull: false
    },
    updatedAt:{
      type: type.STRING,
      allowNull: false
    },
    createdAt:{
      type: type.STRING,
      allowNull: false
    },
  }, {});
     article_comment.associate = function(models) {
    // associations can be defined here
     article_comment.hasMany(models.article_comments_user_ratings,{foreignKey:'comment_id'});
     article_comment.hasMany(models.article_replies,{foreignKey:'comment_id'});
  };
  return article_comment;
};

我的评论等级

'use strict';
module.exports = (sequelize, type) => {
  const article_comments_user_ratings = sequelize.define('article_comments_user_ratings', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: type.INTEGER
    },
    rating:{
      type: type.BOOLEAN,
      allowNull: false
    },
    createdAt: {
      allowNull: false,
      type: type.DATE
    },
    updatedAt: {
      allowNull: false,
      type: type.DATE
    }
  }, {});
  article_comments_user_ratings.associate = function(models) {
    // associations can be defined here
    article_comments_user_ratings.belongsTo(models.article_comments)

  };
  return article_comments_user_ratings;
};

但是,当我使用findOrCreate方法时,它只会执行INSERT INTO "article_comments_user_ratings" ("id","rating","createdAt","updatedAt").,这显然是失败的,因为在数据库中,我还为article_comments_user_ratings表添加了user_id和comment_id列。

这没有任何意义,因为有了sync()函数,在进行迁移之前它就可以正常工作。

我不知道该怎么办?

1 个答案:

答案 0 :(得分:0)

我通过在定义模型后定义关联来解决此问题。

示例:

const User = UserModel(sequelize, Sequelize)
const Comment = CommentsModel(sequelize, Sequelize)

User.hasMany(UserCommentRating,{foreignKey:'user_id'})
Comment.hasMany(UserCommentRating,{foreignKey:'comment_id'})

似乎不推荐使用模型内部的关联。