Sequelize 中的外键

问题描述

我在 postgresql 中有两个表,它们通过外键相互关联。

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));

models 目录中,我有三个文件 index.js、Person.js 和 Car.js。 Person.js 就像

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 就像

module.exports = (sequelize,{
    model:{
        type:DataTypes.STRING(50),allowNull: false
       },primaryKey: true
    }
  },{
    classMethods: {
      associate: function(models) {
       
      }
    }
  });
  return car;
};

我的代码是否正确,外键是否像这样工作?我应该使用 hasMany 吗?我在 index.js 和连接到数据库中还有其他问题,所以我无法在我的机器上测试它。以及如何定义双主键?

解决方法

  1. 尝试将您的关联代码移至 Index.js。在你的 Person.js 中,你导入了汽车模型吗?

  2. 你的问题不是 Clear Pal。您的代码具有一对一 (hasObe) 关联。您要求一对多关联(hasMany)。请说清楚。

请参阅以下有关关联的教程/博客并尝试使用它们。希望他们会有所帮助。

一个。 Tutorial on One to One Assoc。 湾Tutorial on One to Many Assoc.