Foreign Key definitions on Sequelize Models

Eray

I'm trying to create Sequelize (3.20) models of these 2 tables on Postgresql:

| user  |          | comment  |
|-------|          |----------|
| id    |          | id       |
| email |          | userId   |

user table is on crm schema and comment table is on comment schema. comment.userId has foreign key to user.id.

var User = db_conn.define('user', {
  email: {
    ...
  }
}, {
  ...
});
User.sync({force: true}).then(function () {
  return User.create({
    email: '[email protected]'
  });
});

var Comment = db_conn.define('comment', {
  userId: {
    type: Sequelize.INTEGER,
    allowNull: false,
    references: {
        model: User,
        key  : 'id',
        deferrable: Sequelize.Deferrable.INITIALLY_DEFERRED
    }
  }
}, {
  ...
});
Comment.sync({force: true}).then(function () {
  return Comment.create({
    userId: 1,
  });
});

But i'm getting this error:

Unhandled rejection SequelizeDatabaseError: relation "user" does not exist

Generated SQL :

CREATE TABLE IF NOT EXISTS "comment"."comment" ("id"   SERIAL, "userID" INTEGER NOT NULL REFERENCES "user" ("id") DEFERRABLE INITIALLY DEFERRED);

As you see it's creating a FK to user table not 'crm'.'user' table. And it's cauisng error because there is no user table on public schema. Can you please tell me what is I'm missing?

Thank you.

Ezequiel Tolnay

As a workaround until Sequelize has this issue fixed, you could set the search_path of the user you're logging in to the database with, as follows:

ALTER ROLE sequelize_user IN DATABASE my_sequelize_app_db
  SET search_path = crm, comment, public;

That way, the CREATE TABLE statement that's currently failing will work nicely. You would only run into problems if you have tables with same name on different schemas.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related