【问题标题】:Cant seem to set multiple foreign key references to the same model in sequelize, Node似乎无法在 sequelize、Node 中设置对同一模型的多个外键引用
【发布时间】:2019-07-27 01:37:10
【问题描述】:

我有一个正在构建的节点后端,并且我有两个正在使用 sequelize 构建的模型。用户模型和朋友模型。我想在朋友模型(请求者,请求者)中有两个字段,它们从用户模型中引用两个不同的用户。

我现在在 postgres shell 中设置它的方式是只有 1 个对用户模型的引用,即 firends_userId。我想把它改成有两个。

这是我的代码:

型号:

const seq = require('sequelize');
const { postgres } = require('../../index');
const { user } = require('./User')

const friend = postgres.define(
  "friend",
  {
    id: {
      type: seq.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    blocked: {
      type: seq.BOOLEAN,
      default: false,
      null: false
    },
    favorite: {
      type: seq.BOOLEAN,
      default: false,
      null: false
    },
  },{
    createdAt:  seq.DATE,
    updatedAt:  seq.DATE,
  },
);
postgres.sync()
  .then(() => {
    console.log("friend table is synced")
  })
  .catch((error) => {
    console.log("caught error with friend:  " + error)
  })

user.hasMany(friend, {as: 'friender', foreignkey: 'frienderId'});
user.hasMany(friend, {as: 'friended', foreignkey: 'friendedId'});

module.exports.friend = friend;

const seq = require('sequelize');
const { postgres } = require('../../index');

const user = postgres.define(
  "user",
  {
    id: {
      type: seq.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: {
      type: seq.STRING,
      unique: true,
      null: false,
      require: true,
      validate: {
        isAlphanumeric: true,
        allowNull: false,
        len:  [8,16],
      }
    },
    email: {
      type: seq.STRING,
      unique: true,
      null: false,
      require: true,
      validate: {
        isEmail: true,
        allowNull: false,
      }
    },
    password: {
      type: seq.STRING,
      null: false,
      require: true,
      validate: {
        allowNull: false,
        len:  [8, 18],
      }
    },
    first_name: {
      type: seq.STRING,
      null: false,
      require: true,
      validate: {
        allowNull: false,
        isAlpha: true,
      }
    },
    last_name: {
      type: seq.STRING,
      null: false,
      require: true,
      validate: {
        allowNull: false,
        isAlpha: true,
      }
    }
  },{
    createdAt:  seq.DATE,
    updatedAt:  seq.DATE,
  },
);
postgres.sync()
  .then(() => {
    console.log("friend table is synced")
  })
  .catch((error) => {
    console.log("caught error with friend:  " + error)
  })

module.exports.user = user;

这是 postgres shell 中的当前表

splitter=# \d+ friends;
                                                         Table "public.friends"
  Column  |           Type           | Collation | Nullable |               Default               | Storage | Stats target | Description 
----------+--------------------------+-----------+----------+-------------------------------------+---------+--------------+-------------
 id       | integer                  |           | not null | nextval('friends_id_seq'::regclass) | plain   |              | 
 blocked  | boolean                  |           |          |                                     | plain   |              | 
 favorite | boolean                  |           |          |                                     | plain   |              | 
 DATE     | timestamp with time zone |           | not null |                                     | plain   |              | 
 userId   | integer                  |           |          |                                     | plain   |              | 
Indexes:
    "friends_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "friends_userId_fkey" FOREIGN KEY ("userId") REFERENCES users(id) ON UPDATE CASCADE ON DELETE SET NULL

splitter=# 

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    在 Sequelize 模型中,可以通过为多个列指定 primaryKey: true 来编写复合主键,但 Sequelize 目前不支持复合主键,所以没有办法。

    参见https://github.com/sequelize/sequelize/issues/311(与复合外键相关的讨论,这在 squelize 中是不可能的,这直接意味着复合主键也不可能)。

    如果有多个外键指向一个表,可以使用belongsTo方法。

    更多细节可以参考:

    Two foreign Key of same table in one table in sequelize

    文档:

    https://sequelize.readthedocs.io/en/latest/docs/associations/#belongsto

    【讨论】:

    • 我的意思是说外键不是主键
    • 更新了答案,也提供了参考。希望对您有所帮助。
    • 在我查看了您链接的文章后,它起作用了。谢谢
    猜你喜欢
    • 2020-09-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多