Связь Sequelize не синхронизируется с определением модели

'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")., который, очевидно, не работает, потому что в базе данных у меня также есть дополнительные столбцы user_id и comment_id для таблицы article_comments_user_ratings.

В этом нет никакого смысла, потому что с функцией sync () до перехода к миграции она работала.

Я не знаю что делать?


person calimses    schedule 05.10.2019    source источник


Ответы (1)


Я исправил эту проблему, определив ассоциации после определения модели.

Пример:

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

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

Кажется, что ассоциации внутри модели устарели.

person calimses    schedule 05.10.2019