User 和 Contact 模型之间的关联正确吗?

The association between User and Contact model sound and correct?

两个模型,UserContactpostgressequelize 中。联系人是一个用户,它有一个所有者 (my_id),并且可能有多个联系人。

Contact: {
  my_id, integer
  contact_user_id: integer
}

User: {
  id: integer
  name: string
}

这里是定义的关联:

  Contact.belongsTo(User, {foreignKey: "my_id"});
  Contact.belongsTo(User, {foreignKey: "contact_user_id"});
  User.hasMany(Contact, {foreignKey: "contact_user_id"});
  User.hasOne(Contact, {foreignKey: "my_id"});

一个联系人通过 my_idcontact_user_idUser 有 2 个 belongsTo 关联。同时还有一个用户 hasMany 联系人和 hasOne 所有者联系人。这些关联是否正确?

差不多吧。您需要向这些关联添加一个 as: 参数(并在查询时使用这些值),以便 Sequelize 可以确定哪个连接是合适的。

例如:

  User.hasMany(Contact, {as: 'contactFor', foreignKey: "contact_user_id"});
  User.hasOne (Contact, {as: 'mycontact',  foreignKey: "my_id"}); 

  User.findAll({
     where: {'id' : 1},
     include: [{ model: Contact, as: 'contactFor'}]
  });

以上查询将显示用户 1 和所有将用户 1 列为其联系人的联系人....生成的查询将显示如下内容:

 SELECT * FROM user JOIN contact 
 ON user.id = contact.contact_user_id 
 WHERE user.id = 1

HTH