尝试使用sequelize(3.3.2)在PostgreSQL数据库中创建关系。我正在使用grunt(在发出命令之后没有错误,我正在使用generator-sql-fullstack)。创建了DB表,但没有关系,也没有外键。这是我的模特:
user.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;
};
cart.model.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 comand之后从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;
答案 0 :(得分:0)
解决方案是从classMethods中删除关联定义并在模型类中创建函数:
user.js
User.associate = function(models) {
User.hasMany(models.cart)
}
index.js
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});