gpt4 book ai didi

javascript - Sequelize 与 PostgreSQL 的关系 (generator-sql-fullstack)

转载 作者:行者123 更新时间:2023-11-29 12:25:39 26 4
gpt4 key购买 nike

尝试使用 sequelize (3.3.2) 在我的 PostgreSQL 数据库中创建关系。我正在使用 grunt(在 serve 命令之后没有错误,我正在使用 generator-sql-fullstack)。创建了数据库表,但没有关系也没有外键。这是我的模型:

用户.model.js

'use strict';

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('user', {

user_id: {
type: DataTypes.STRING//,
// primaryKey: true
},

username: {
type: DataTypes.STRING,
unique: true,
alowNull: false
},

password: {
type: DataTypes.STRING,
alowNull: false
},

user_role: {
type: DataTypes.STRING,

}
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.cart)
}
}
});

User
.sync({
force: true
})
.then(function() {
User.create({
user_id: 1,
username: 'test_username',
password: 'some_pass'
});

});

return User;
};

购物车模型.js

'use strict';

module.exports = function(sequelize, DataTypes) {
var Cart = sequelize.define('cart', {
cart_id: {
type: DataTypes.STRING,
primaryKey: true
}
});

Cart
.sync({force: true})
.then(function (){
Cart.create({
cart_id: 12
});

});

return Cart;
};

在 grunt serve 命令后从 pgadmin 登录:

-- Table: public.carts

-- DROP TABLE public.carts;

CREATE TABLE public.carts
(
cart_id character varying(255) NOT NULL,
"createdAt" timestamp with time zone NOT NULL,
"updatedAt" timestamp with time zone NOT NULL,
CONSTRAINT carts_pkey PRIMARY KEY (cart_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.carts
OWNER TO postgres;


-- Table: public.users

-- DROP TABLE public.users;

CREATE TABLE public.users
(
id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
user_id character varying(255),
username character varying(255),
password character varying(255),
user_role character varying(255),
"createdAt" timestamp with time zone NOT NULL,
"updatedAt" timestamp with time zone NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (id),
CONSTRAINT users_username_key UNIQUE (username)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.users
OWNER TO postgres;

最佳答案

解决方案是从 classMethods 中删除关联定义并在模型类中创建函数:

用户.js

User.associate = function(models) {
User.hasMany(models.cart)
}

索引.js

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

关于javascript - Sequelize 与 PostgreSQL 的关系 (generator-sql-fullstack),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324972/

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