我无法将数据插入Sequelize中的表(具体是外键)

时间:2018-03-01 20:35:00

标签: javascript postgresql sequelize.js

所以我在我的JavaScript应用程序上使用Sequelize作为我的PostgreSQL数据库。我有4个模型(用户,帖子,喜欢和关注跟随者)。我的用户模型工作正常,它没有任何外键,所以我能够创建和查找数据没有任何问题。但是,我的Posts模型有2个外键(user_id和parent_id)。 user_id引用Users表中的主键(id),parent_id引用自身的主键(id)(Posts表)。当我尝试将数据插入Posts表时,我能够在常规字段中插入数据,但外键只是被忽略。

这是我的数据库连接:

const Sequelize = require('sequelize');
const API = require('../../client/public/config.js');
const db = new Sequelize(API.elephantSqlUrl);

db.authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch((err) => {
    console.error('Unable to connect to the database:', err);
  });

module.exports = db;

这是我的用户模型:

const Sequelize = require('sequelize');
const db = require('../db.js');

const Users = db.define('users', {
  username: {
    type: Sequelize.STRING,
    unique: true
  },
  bio: Sequelize.STRING,
  profile_picture: Sequelize.STRING
});

module.exports = Users;

这是我的帖子模型:

const Sequelize = require('sequelize');
const db = require('../db.js');

const Posts = db.define('posts', {
  type: Sequelize.INTEGER,
  body: Sequelize.STRING,
  likesCount: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  }
});

module.exports = Posts;

这是我定义外键并同步我的数据库的地方:

const db = require('./db.js');
const Users = require('./models/users.js');
const Posts = require('./models/posts.js');
const Likes = require('./models/likes.js');
const FollowingsFollowers = require('./models/followingsFollowers.js');

Posts.belongsTo(Users, { foreignKey: 'user_id' });
Users.hasMany(Posts, { foreignKey: 'user_id' });
Posts.belongsTo(Posts, { foreignKey: 'parent_id' });
Posts.hasMany(Posts, { foreignKey: 'parent_id' });
Likes.belongsTo(Posts, { foreignKey: 'post_id' });
Posts.hasMany(Likes, { foreignKey: 'post_id' });
Likes.belongsTo(Users, { foreignKey: 'user_id' });
Users.hasMany(Likes, { foreignKey: 'user_id' });
FollowingsFollowers.belongsTo(Users, { foreignKey: 'following_id' });
Users.hasMany(FollowingsFollowers, { foreignKey: 'following_id' });
FollowingsFollowers.belongsTo(Users, { foreignKey: 'follower_id' });
Users.hasMany(FollowingsFollowers, { foreignKey: 'follower_id' });

db.sync({ force: true })
  .then(() => {
    console.log('db synced');
  })
  .catch(() => {
    console.log('error syncing db');
  });

这是我尝试添加帖子的地方:

const addPost = (username, post) => {
  return new Promise((resolve, reject) => {
    Users.findOne({ where: { username: username } })
      .then((user) => {
        post.user_id = user.id;

        Posts.create()
          .then((created) => {
            resolve();
          });
      })
      .catch((err) => {
        reject(err);
      });
  });
};

当我使用用户名和对象调用此函数时,使用"键入"和"身体"键,一个帖子被创建。但是,帖子包含" id"," type"," body"," likesCount"," createdAt",以及" updatedAt"领域。 " user_id"字段永远不会被添加到那里。

3 个答案:

答案 0 :(得分:0)

我不知道这是否会解决您的问题,但您没有将任何参数传递给create()方法。 post对象传递给函数,使用user_id和...忽略。

不应该是这样吗?:

(...)
Posts.create(post)
(...)

答案 1 :(得分:0)

我能够解决它。我的解决方案是在我的模型文件上添加外键关系,如下所示:

ORDER BY

然后对于我同步我的数据库的文件,这就是我要做的所有事情,如下:

const Sequelize = require('sequelize');
const Users = require('./users.js');
const db = require('../db.js');

const Posts = db.define('posts', {
  type: Sequelize.INTEGER,
  body: Sequelize.STRING,
  likesCount: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  }
});

Posts.belongsTo(Users, { foreignKey: 'user_id' });
Posts.belongsTo(Posts, { foreignKey: 'parent_id' });

module.exports = Posts;

答案 2 :(得分:0)

1. Add user_id as foreign key in posts model and other models where realtion with users required.
2.Define your Posts models as:
const Posts = db.define('posts', {
  type: Sequelize.INTEGER,
  user_id: Sequelize.INTEGER,
  body: Sequelize.STRING,
  likesCount: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  }
});
3. Remove Posts.belongsTo(Posts, { foreignKey: 'parent_id' }); not required