mysql - Sequelize 错误 : you must use the 'as' keyword to specify the alias of the association you want to include. - node.js

标签 mysql node.js express sequelize.js mysql2

我正在制作一个类似于“Twitter”的网络应用程序。

当我运行服务器时,

'用户多次关联到用户。要确定正确的关联, 您必须使用“as”关键字来指定要包含的关联的别名。 <- 这条消息出现了。

我为“followers”和“followings”之间的关系应用了“as”关键字。 但错误消息不断出现。

我确定我做错了什么,但我不知道到底是什么。 有人可以帮帮我吗?

  1. 模型/index.js

    'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
    sequelize = new Sequelize(process.env[config.use_env_variable], config);
  } else {
      sequelize = new Sequelize(config.database, config.username, config.password, config);
  }

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.User = require('./user')(sequelize, Sequelize);
db.Post = require('./post')(sequelize, Sequelize);
db.Hashtag = require('./hashtag')(sequelize, Sequelize);

db.User.hasMany(db.Post); //1 : n
db.Post.belongsTo(db.User); 
// m: n
db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
db.Hashtag.belongsToMany(db.Post, { through: 'PostHashtag' });

// I use alias here *****
db.User.belongsToMany(db.User, {
  foreignKey: 'followingId',
  as: 'Followers',
  through: 'Follow',
});

db.User.belongsToMany(db.User, {
  foreignKey: 'followerId',
  as: 'Followings',
  through: 'Follow',
});

module.exports = db; 

  1. models/user.js
    module.exports = (sequelize, DataTypes) => (
  sequelize.define('user', {
    email: {
      type: DataTypes.STRING(40),
      allowNull: true,
      unique: true,
    },
    nick: {
      type: DataTypes.STRING(15),
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    provider: {
      type: DataTypes.STRING(10),
      allowNull: false,
      defaultValue: 'local',
    },
    snsId: {
      type: DataTypes.STRING(30),
      allowNull: true,
    },
  }, {
    timestamps: true,
    paranoid: true,
  })
);


  1. 模型/post.js
module.exports = (sequelize, DataTypes) => (
  sequelize.define('user', {
    email: {
      type: DataTypes.STRING(40),
      allowNull: true,
      unique: true,
    },
    nick: {
      type: DataTypes.STRING(15),
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    provider: {
      type: DataTypes.STRING(10),
      allowNull: false,
      defaultValue: 'local',
    },
    snsId: {
      type: DataTypes.STRING(30),
      allowNull: true,
    },
  }, {
    timestamps: true,
    paranoid: true,
  })
);

  1. 模型/hashtag.js

module.exports = (sequelize, DataTypes) => (
    sequelize.define('hashtag', {
        title: {
            type: DataTypes.STRING(15),
            allowNull: false,
            unique: true,
        },
    }, {
        timestamps: true,
        paranoid: true,
    })
); 

最佳答案

我认为这将解决您的问题,您必须创建一个表follower,然后将它与具有以下和关注者别名的用户表相关联,并使用它来查询关注者和关注

追随者模型

module.exports =   (sequelize, datatypes) => {
     sequelize.define('follower', {
        _id: {
            type: datatypes.integer,
            allownull: false,
            primarykey: true,
            autoincrement: true
        },
        userid: {
            type: datatypes.integer,
            allownull: false
        },
        followingid: {
            type: datatypes.integer,
            allownull: false
        }
    });
} 

协会

db.follower.belongsTo(db.user, {
    as: 'following',
    foreignkey: 'followingid'
});

db.follower.belongsto(db.user, {
    as: 'follower',
    foreignkey: 'userid'
});

查询获取关注者

follower.findall({
    where: {
        followingid: userid
    },
    attributes: ['_id'],
    include: [{
        model: user, attributes:
            ['fullname', 'username', '_id', 'picture'],
        as: 'follower'
    }]
})

关于mysql - Sequelize 错误 : you must use the 'as' keyword to specify the alias of the association you want to include. - node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64799742/

相关文章:

php - 将两个表合并为一个

python - python向mysql插入中文字符时出现UnicodeEncodeError

mysql - 用户个人资料不显示其数据

mysql - 如何使用 nodejs 和 pem key 文件连接到 Cloud SQL 实例

javascript - 在 JavaScript 中创建动态正则表达式匹配

node.js - 服务器端不进行排序

用于获取两个日期中较晚日期的 Mysql 日期函数

javascript - 使用node-http-proxy在同一子域下代理 Node 服务器和websocket服务器

node.js - Express 3 和 EJS 中的布局

node.js - 如何在 NodeJS 上访问 socket.io 中的 cookie-session 中间件?