代码之家  ›  专栏  ›  技术社区  ›  Hide

sequelize表未与用户关联

  •  1
  • Hide  · 技术社区  · 6 年前

    我使用node.js作为api服务器,使用sequelize(版本4)与mysql通信。

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

    [型号.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'});

    与外键连接的关联。

    路由器也在这里。

    [路由器.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"})
        })
    }
    

    我想用follower查看用户信息,所以我定义了 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'}
        ]
    

    它工作得很好。输出在这里(我已读取插入用户 hide test . 还有

    {
      "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 用户ID 是吗?

    我只想展示 用户ID

    1 回复  |  直到 6 年前
        1
  •  3
  •   PhilippeAuriach    6 年前

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

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

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

    [编辑]您可以尝试使用选项。包括[].through.attributes以从through模型中删除不需要的属性。下次请记住,你应该提出不同的问题