{ const User = s-6ren">
gpt4 book ai didi

postgresql - Sequelize throw : "relation "users"does not exist"

转载 作者:行者123 更新时间:2023-12-03 22:37:08 25 4
gpt4 key购买 nike

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

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;
};

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

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";

物品属性由正确的“物品”前置,但用户前置的“用户”不正确。也不确定为什么它说 FROM "users" AS "User" 而不是 FROM "Users"
在我的配置中,我使用了 underscored: true 并且我使用的是 postgres 数据库。我的 postgres 数据库中有一个“用户”表和一个“项目”表。

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

最佳答案

从以下位置切换 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 需要配置中的数据库 key !

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

关于postgresql - Sequelize throw : "relation "users"does not exist",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com