簡體   English   中英

續集關聯不與 model 定義同步

[英]Sequelize association not syncing with model definition

'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() function,在遷移到遷移之前,它正在工作。

我不知道該怎么辦?

我通過在定義 model 后定義關聯來解決此問題。

例子:

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

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

似乎不推薦使用 model 中的關聯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM