最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sequelize关联未与模型定义同步

运维笔记admin13浏览0评论

Sequelize关联未与模型定义同步

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").,这显然是失败的,因为在数据库中,我还为article_comments_user_ratings表添加了user_id和comment_id的其他列。

这没有任何意义,因为使用sync()函数,在进行迁移之前,它已经起作用了。

我不知道该怎么办?

回答如下:我在定义模型后通过定义关联来解决此问题。

示例:

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

似乎模型中的关联已被弃用。 
发布评论

评论列表(0)

  1. 暂无评论