Home > Mobile >  sequelize manytomany relation with data missing on result
sequelize manytomany relation with data missing on result

Time:04-01

I am using sequelize with postgreSQL and nodejs.

my database has 3 relations,

1 relation user,

1 relation link,

1 relation table user_has_link (it's a relation table between user and link) with 3 column :

my sequelize relation models beween link and user:

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

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

and finally my query to get a user informations:

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

the request to database is OK, but i am missing the url_link of the user ( i don't understandt why):

for example a response of teh request:

avatarKey: "thumbnail-fce0848f-9509-4180-b7fa-c2bf908ed396.png"
email: "[email protected]"
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, …}

thanks a lot for your help Cyrille

CodePudding user response:

You should define a junction table model explicitly with all extra fields you need and indicate it instead of using the string user_has_link in belongsToMany, see advanced many-to-many

CodePudding user response:

following advice of Anatoly, I have updated my belongToMany relation.

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

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

I have all my data, included url_link

{
  "id": 2,
  "login": "aviateur22",
  "email": "[email protected]",
  "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"

thanks you

  • Related