Hide
Hide

Reputation: 3317

sequelize table is not associated to user

I use Node.js for Api server and sequelize(version 4) to communicate with MySQL.

Final goal is implement follow&following system. (It is already implemented and Now I struggle with view user information with associated followers)

[model.js]

import Sequelize from 'sequelize';

export const sequelize = new Sequelize('db', 'id', 'pw', {
    host: '127.0.0.1',
    dialect: 'mysql'
});

export const User = sequelize.define('user', {
    no: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        unique: true
    },
    userid: {
        type: Sequelize.STRING,
        allowNull: false,
        primaryKey: true,
    },
    userpw: {
        type: Sequelize.STRING,
        allowNull: false
    }
}, {
    freezeTableName: true,
    underscored: true
})

User.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id'});
User.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id'});

sequelize.sync({
    force: false
}, () => console.log("[*] DB Sync complete"));

In above code, I defined

User.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id'}); User.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id'});

association to connect with foreign key.

Also router is here.

[router.js]

import { User, sequelize } from '../model';
export const getUser = (req, res) => {
    User.find({
        where: {
            userid: req.params.id
        },
        include: [
            {model: sequelize.model("follow")}
        ]
    })
    .then(result => {
        res.status(200).json({status: true, result: result})
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({status: false, result: "getUser error"})
    })
}

I want to view user information with follower, So I defined include: [ {model: sequelize.model("follow")} ]

But when I access to /user/test, it throw error like this -> SequelizeEagerLoadingError: follow is not associated to user!

I already defined about relationship. Why this error occured?

[Current result]

{
  "status": true,
  "result": {
    "no": 1,
    "userid": "girim",
    "userpw": "$2a$10$LnN1UmtKM//8qkze6j6CkuoISl6jh63HUURbmbH6xFVTL3GVWDux.",
    "created_at": "2018-07-19T01:39:43.000Z",
    "updated_at": "2018-07-19T01:39:43.000Z"
  }
}

[Desired result]

{
  "status": true,
  "result": {
    "no": 1,
    "userid": "girim",
    "userpw": "$2a$10$LnN1UmtKM//8qkze6j6CkuoISl6jh63HUURbmbH6xFVTL3GVWDux.",
    "created_at": "2018-07-19T01:39:43.000Z",
    "updated_at": "2018-07-19T01:39:43.000Z",
    "followers": [
     // follower list here!
    ]
  }
}

How can I fix it?

Thanks.


After editing code,

    include: [
        { model: User, as: 'follower'}
    ]

it works fine. output is here. (I alread insert user hide and test. And also

{
  "status": true,
  "result": {
    "no": 3,
    "userid": "hide",
    "userpw": "$2a$10$oN/.mEuSb8RzRkK.NdyNP.ZbkvcWOSMSsMnxmR.jRWB6wodFTyI02",
    "created_at": "2018-07-19T06:01:17.000Z",
    "updated_at": "2018-07-19T06:01:17.000Z",
    "follower": [
      {
        "no": 1,
        "userid": "test",
        "userpw": "$2a$10$dVdZ80LYBX9hPsCCfwLC8uhqZD1oWXKyzzIb59m/TOwWr.A5r4rT.",
        "created_at": "2018-07-19T06:00:57.000Z",
        "updated_at": "2018-07-19T06:00:57.000Z",
        "follow": {
          "created_at": "2018-07-19T06:02:09.000Z",
          "updated_at": "2018-07-19T06:02:09.000Z",
          "following_id": "test",
          "follower_id": "hide"
        }
      }
    ]
  }
}

But I want to print out only userid in followers.

So I add attributes option like this.

{ model: User, as: 'follower', attributes: ['userid']},

And output is here.

{
  "status": true,
  "result": {
    "no": 3,
    "userid": "hide",
    "userpw": "$2a$10$oN/.mEuSb8RzRkK.NdyNP.ZbkvcWOSMSsMnxmR.jRWB6wodFTyI02",
    "created_at": "2018-07-19T06:01:17.000Z",
    "updated_at": "2018-07-19T06:01:17.000Z",
    "follower": [
      {
        "userid": "test",
        "follow": {
          "created_at": "2018-07-19T06:02:09.000Z",
          "updated_at": "2018-07-19T06:02:09.000Z",
          "following_id": "test",
          "follower_id": "hide"
        }
      }
    ]
  }
}

Is there any solutio to remove follow under the userid?

I want to only show userid

Upvotes: 1

Views: 5674

Answers (1)

PhilippeAuriach
PhilippeAuriach

Reputation: 2447

The include part is not correct. You should include the model you want (User) with the correct as, so to query the user and its followers :

User.find({
    where: {
        userid: req.params.id
    },
    include: [
        { 
            model: User, 
            as: 'followers',
            through: {attributes: []}
        }
    ]
})

Also, you should change your association definition which read as: 'follower' instead of as: 'followers'

[EDIT] you may try with options.include[].through.attributes to remove unwanted attributes from the through model. Please keep in mind next time, that you should create separate questions

Upvotes: 3

Related Questions