sequelize表未与用户关联

时间:2018-07-19 05:46:01

标签: node.js sequelize.js

我将Node.js用于Api服务器,并使用sequelize(版本4)与MySQL进行通信。

最终目标是实施跟踪和跟踪系统。 (它已经实施,现在我很难与相关的关注者一起查看用户信息)

[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"));

在上面的代码中,我定义了

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

与外键关联的关联。

这里还有路由器。

[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"})
    })
}

我想与关注者一起查看用户信息,因此我定义了include: [ {model: sequelize.model("follow")} ]

但是当我访问/ user / test时,它会引发如下错误-> SequelizeEagerLoadingError: follow is not associated to user!

我已经定义了关系。为什么会发生此错误?

[当前结果]

{
  "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"
  }
}

[所需结果]

{
  "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!
    ]
  }
}

我该如何解决?

谢谢。


编辑代码后,

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

它工作正常。输出在这里。 (我已经插入了用户hidetest。还有

{
  "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"
        }
      }
    ]
  }
}

但是我只想在关注者中打印出userid

所以我添加了attributes这样的选项。

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

输出在这里

{
  "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"
        }
      }
    ]
  }
}

follow下是否有任何解决方案可以去除userid

我只想显示userid

1 个答案:

答案 0 :(得分:3)

包含部分不正确。您应该使用正确的as包括所需的模型(用户),以便查询用户及其关注者:

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

此外,您应该更改关联定义,该定义应读为as: 'follower',而不是as: 'followers'

[编辑],您可以尝试使用options.include []。through.attributes从穿通模型中删除不需要的属性。下次请记住,您应该创建单独的问题