Sequelize关联未与模型定义同步

问题描述 投票:0回答:1
'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()函数,在进行迁移之前,它已经起作用了。

我不知道该怎么办?

javascript node.js sequelize.js sequelize-cli
1个回答
0
投票
我在定义模型后通过定义关联来解决此问题。

示例:

const User = UserModel(sequelize, Sequelize) const Comment = CommentsModel(sequelize, Sequelize) User.hasMany(UserCommentRating,{foreignKey:'user_id'}) Comment.hasMany(UserCommentRating,{foreignKey:'comment_id'})

似乎模型中的关联已被弃用。 
© www.soinside.com 2019 - 2024. All rights reserved.