Sequelize-如何包括自定义列的详细信息

时间:2018-10-18 16:02:36

标签: javascript node.js sequelize.js

我有2个表:用户跟随者

基本架构如下:

用户表

var User = sequelize.define(
    "User",
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      username: DataTypes.STRING,
    },
    {
      timestamps: true,
      tableName: "users",
      underscored: true
  ); 

  //Associations;
  User.associate = function(models) {
      User.hasMany(models.Follower, {
        constraints: false,
        onDelete: "cascade",
        hooks: true
      })
  };

追随者表

var Follower = sequelize.define(
    "Follower",
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      follower_id: {
        type: DataTypes.INTEGER,
        foreignKey: true
      },
      following_id: {
        type: DataTypes.INTEGER,
        foreignKey: true
      }
    },
    {
      timestamps: true,
      tableName: "followers",
      underscored: true
    }
  ); 

  //Associations;
  Follower.associate = function(models) {
    Follower.belongsTo(models.User, {
      foreignKey: "following_id",
      constraints: false
    }),
    Follower.belongsTo(models.User, {
      foreignKey: "follower_id",
      constraints: false
    });
  };

我想获取用户的关注者列表,但我想向用户显示他们关注的对象,现在是他们自己的数据。

我当前正在运行此过程:

const following = await models.Follower.findAndCountAll({
    attributes: models.Follower.fields,
    where: { follower_id: user_id },
    include:[
      {
        model: models.User,
        attributes: models.User.fieldsPublic,
        required: yes
      }
    ]
})

问题在于include返回的是当前用户,而不是他们关注的人的用户详细信息。

本质上,连接似乎在User.id = Follower.follower_id

之间

如何将其添加到include并加入User.id = Follower.following_id

1 个答案:

答案 0 :(得分:0)

您既可以在模型定义中添加as,也可以包括include以便定义应该使用哪个外键(docs

也是这样:

Follower.associate = function(models) {
    Follower.belongsTo(models.User, {
      foreignKey: "following_id",
      as: 'following',
      constraints: false
    }),
    Follower.belongsTo(models.User, {
      foreignKey: "follower_id",,
      as: 'follower',
      constraints: false
    });
  };

...
include:[
      {
        model: models.User,
        attributes: models.User.fieldsPublic,
        as: 'follower'
        required: yes
      }
    ]
...

或者,您可以删除required: yes并使用where属性定义连接条件

此外,include似乎有一个on属性,据说该属性类似于where(根据docs),但是我找不到一个示例。