sequelize manytomany 关系与数据丢失的结果

sequelize manytomany relation with data missing on result

我正在将 sequelize 与 postgreSQL 和 nodejs 结合使用。

我的数据库有 3 个关系,

1 关系 用户,

1 关系 link,

1 关系 table user_has_link(这是用户和 link 之间的关系 table),有 3 列 :

我在 link 和用户之间的续集关系模型:

User.belongsToMany(Link,{
    as: 'usersLinks',
    through: 'user_has_link',
});

Link.belongsToMany(User,{
    as: 'linksUsers',
    through: 'user_has_link'
});

最后是我获取用户信息的查询:

const user = await User.findByPk(userId,
 {
     include:{
          model: Link, as: 'usersLinks'
     }
 });   

对数据库的请求没问题,但我缺少用户的url_link(我不明白为什么):

例如请求的响应:

avatarKey: "thumbnail-fce0848f-9509-4180-b7fa-c2bf908ed396.png"
email: "aviateur@ht.fr"
id: 2
login: "aviateur22"
sex: "homme"
usersLinks: Array(2)
0: {id: 1, compagny_name: 'github', picture_name: 'github.png', created_at: '2022-03-30T13:02:31.920Z', updated_at: null, …}
1: {id: 2, compagny_name: 'linkedin', picture_name: 'linkedin.png', created_at: '2022-03-30T13:02:31.920Z', updated_at: null, …}

非常感谢您的帮助 西里尔

您应该明确定义一个连接 table 模型,其中包含您需要的所有额外字段并指明它,而不是在 belongsToMany 中使用字符串 user_has_link,请参阅 advanced many-to-many

根据 Anatoly 的建议,我更新了我的 belongToMany 关系。

const UserLink = require('./userLink');

User.belongsToMany(Link,{
    as: 'usersLinks',
    through: UserLink,
});

我有我所有的数据,包括 url_link

{
  "id": 2,
  "login": "aviateur22",
  "email": "aviateur@hotmail.com",
  "sex": "homme",
  "avatarKey": "thumbnail-fce0848f-9509-4180-b7fa-c2bf908ed396.png",
  "usersLinks": [
    {
      "id": 1,
      "compagny_name": "github",
      "picture_name": "github.png",
      "created_at": "2022-03-30T13:02:31.920Z",
      "updated_at": null,
      "UserLink": {
        "user_id": 2,
        "link_id": 1,
        "link_url": "https://github.com/aviateur22",
        "created_at": "2022-03-31T07:10:32.010Z",
        "updated_at": "2022-03-31T07:11:47.370Z",
        "UserId": 2,
        "LinkId"

谢谢你