顺序抛出:“关系“用户”不存在”

时间:2019-09-14 02:39:22

标签: postgresql sequelize.js sequelize-cli

我有一个与我的Item模型具有hasMany关联的User模型:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    underscored: true,
  });
  User.associate = function(models) {
    // associations can be defined here
    User.hasMany(models.Item, {
      onDelete: 'CASCADE'
    })
  };
  return User;
};

我有一个属于用户的Item模型:

module.exports = (sequelize, DataTypes) => {
  const Item = sequelize.define('Item', {
    title: DataTypes.STRING,
    link: DataTypes.STRING,
    user_id: DataTypes.INTEGER
  }, {
    underscored: true,
  });
  Item.associate = function (models) {
    // associations can be defined here
    Item.belongsTo(models.User)
  };
  return Item;
};

当我执行User.findAll()

我收到错误relation "users" does not exist

这是执行的原始SQL:

SELECT 
  "User"."id", "User"."first_name", "User"."last_name", "User"."email", 
  "User"."created_at" AS "createdAt", "User"."updated_at" AS "updatedAt", 
  "Items"."id" AS "Items.id", "Items"."title" AS "Items.title", 
  "Items"."link" AS "Items.link", "Items"."user_id" AS "Items.user_id", 
  "Items"."created_at" AS "Items.createdAt", "Items"."updated_at" AS "Items.updatedAt", 
  "Items"."user_id" AS "Items.UserId" 
FROM "users" AS "User" 
LEFT OUTER JOIN "items" AS "Items" ON "User"."id" = "Items"."user_id";

Items属性以正确的“ Items”作为前缀,而Users则以不正确的“ User”作为前缀。还不确定为什么会说FROM "users" AS "User"而不是FROM "Users"

在我的配置中,我使用了underscored: true,并且我使用的是postgres数据库。我的postgres数据库中有一个“用户”表和一个“项”表。

"pg": "^7.12.1",
"sequelize": "^5.18.4"
"sequelize-cli": "^5.5.1"

1 个答案:

答案 0 :(得分:0)

从以下位置切换config / config.js:

require('dotenv').config()

module.exports = {
  development: {
    url: process.env.DEV_DATABASE_URL,
    dialect: 'postgres'
  }
}

收件人:

require('dotenv').config()

module.exports = {
  development: {
    url: process.env.DEV_DATABASE_URL,
    database: 'database_development',
    dialect: 'postgres'
  }
}

Sequelize需要配置中的数据库密钥!

https://github.com/sequelize/cli/blob/77a9a76420e36cfbcb82fe3c9c6a12d52c768104/src/commands/database.js#L88