node.js - REFERENCE KEY in node-orm2 -
i working on rest api based on node.js , chose postgresql
database store data. suppose database has 2 tables names user
, comment
. comment
belongs 1 user
, when decide remove user
, comment
's of him/her must removed. so, designed table follows:
create table user( user_id serial, username varchar(32) not null, password varchar(32) not null, constraint pk_user primary key (user_id), constraint uq_user unique (username) ) create table comment( comment_id serial, user_id integer not null, content text not null, constraint pk_cmnt primary key (comment_id), constraint fk_cmnt foreign key (user_id) references user(user_id) on update cascade on delete cascade )
but don't run code , use node-orm2
instead. designed 2 simple models handle simple code:
var user = db.define('user', { username: { type: 'text', size: 32, // varchar(32) required: true, // not null unique: true // unique index }, password: { type: 'text', size: 32, // varchar(32) required: true // not null } }, { id: 'user_id' //serial }); var cmnt = db.define('comment', { content: { type: 'text', required: true // not null } }, { id: 'comment_id' //serial }); cmnt.hasone('user', user, {required: true}); // create association key
and synchronize database these models :
db.sync();
now, want insert new comment belongs user user_id doesn't exist. so, comment
model accepts , insert row comment
table.
my question is, how can things reference key
, on update cascade on delete cascade
?
thanks in advance :)
try use deferrable this:
create table comment( comment_id serial, user_id integer not null, content text not null, constraint pk_cmnt primary key (comment_id), constraint fk_cmnt foreign key (user_id) references user(user_id) on update cascade on delete cascade deferrable deferred )
Comments
Post a Comment