Home > Software design >  Creating a foreignKey in sequelize, that is not a integer association
Creating a foreignKey in sequelize, that is not a integer association

Time:12-17

I want to translate this psql table creation query to sequelize:

PSQL:

CREATE TABLE categories
(
    id INTEGER NOT NULL PRIMARY KEY,
    name CHARACTER VARYING(50) NOT NULL UNIQUE,
    description CHARACTER VARYING(100) NOT NULL
);

CREATE TABLE posts
(
    id INTEGER NOT NULL PRIMARY KEY,
    title CHARACTER VARYING(50) NOT NULL,
    content CHARACTER VARYING(100) NOT NULL,
    from_category CHARACTER VARYING(50) NOT NULL,
    
     CONSTRAINT fk_from_category
      FOREIGN KEY(from_category) 
      REFERENCES categories(name)
)

Its a simple fk association, with varchar type.

I have read sequelize docs, but i still don't know how to change the relation from primary keys to varchar.

From what i read, this is what you can do with associations:

Post.belongsTo(Category, {
  foreignKey: {
    onDelete: ...,
    onUpdate: ...,
    validate: {...},
  },
});

and thats all i could find about on youtube too..

I would be really happy if you can help me. I have spent too much time on this already, but i want it to work!

CodePudding user response:

Follow this example using belongsTo:

class Category extends Model { }
Category.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: false
  },
  description: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, { sequelize, modelName: 'categories' });

class Post extends Model { }
Post.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false
  },
  content: {
    type: DataTypes.STRING,
    allowNull: false
  },
  from_category: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, { sequelize, modelName: 'posts' });

Post.belongsTo(Category, {
  foreignKey: 'from_category',
  targetKey: 'name'
});

Read more about to understand with more details in the official docs.

  • Related