MobiusT
MobiusT

Reputation: 95

Foreign Keys in Sequelize

I have two tables in postgresql and they are associated to each other with a foreign key.

CREATE TABLE Car(
car_id smallint primary key,
model varchar(50) not null
);

CREATE TABLE Person(
first_name varchar(20),
last_name varchar(20),
car_id  smallint,
constraint primary key(first_name, last_name)
constraint fk foreign key(car_id) references Car(car_id));

In models directory I have three files index.js, Person.js and Car.js. Person.js is like

module.exports = (sequelize, DataTypes) => {
  var person= sequelize.define('person', {
    name:{
        type:DataTypes.STRING(50),
        primaryKey:true
    },
    car_id:{
        type:DataTypes.INTEGER,
       
    }
  }, {
    classMethods: {
      associate: function(models) {
       person.hasOne(Car, {
            foreignKey: 'car_id'
          });
      }
    }
  });
  return person;
};

Car.js is like

module.exports = (sequelize, DataTypes) => {
  var person= sequelize.define('person', {
    model:{
        type:DataTypes.STRING(50),
        allowNull: false
       },
    car_id:{
        type:DataTypes.INTEGER,
        primaryKey: true
    }
  }, {
    classMethods: {
      associate: function(models) {
       
      }
    }
  });
  return car;
};

Is my code correct and does foreign key work like this? Should I use hasMany instead? I have other problems in index.js and connecting to database so I cannot test it in my machine. And also how to define double primary keys?

Upvotes: 0

Views: 3186

Answers (1)

BelkeriSai
BelkeriSai

Reputation: 40

  1. Try moving your Associations code to Index.js. In your Person.js, Have you imported Car Model?

  2. Your Question is not Clear Pal. Your code has a One-to-one (hasObe) Association. You are asking for One-to-Many associations (hasMany). Please make it clear.

Refer to the below Tutorials/Blogs on Associations and try them. Hope they will help.

a. Tutorial on One to One Assoc. b. Tutorial on One to Many Assoc.

Upvotes: 1

Related Questions