【问题标题】:How to join twice a single table in sequelize using following and followers example如何使用以下和关注者示例在 sequelize 中加入两次单个表
【发布时间】:2018-02-19 00:44:32
【问题描述】:

这段代码运行良好。我现在可以获得关注和关注者,我需要查看我获得的关注者是否也在关注他们?

这是我如何对关注者表进行另一个查询/子查询并看到我也在关注我的关注者的问题。

关注者表

export default function(sequelize, DataTypes) {
  return 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'
          }
        ]
    })

更新

我已经实现了表单行查询的预期结果:

SELECT  F.userId, F.`followingId` , F1.`followingId` as IsFollowing , U.`fullName` FROM Followers as F

INNER JOIN Users as U ON userId = U._id

LEFT JOIN Followers as F1 On F.userId = F1.followingId

WHERE F.followingId = 142 

还在苦苦挣扎。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    要将您的行查询转换为 sequlize 请求,请尝试以下操作:

    协会

    db.Follower.belongsTo(db.User, {as: 'following', foreignKey: 'followingId', sourceKey: 'userId'});
    db.Follower.hasOne(db.User, {as: 'follower', foreignKey: 'userId'});
    

    查询

    Follower.findAll({
      where: {
        followingId: userId
      },
      attributes: ['userId', 'followingId'],
      include: [
        {
          model: User,
          attributes: ['fullName'],
          as: 'follower',
          required: true // to get inner join
        },
        {
          model: Follower,
          attributes: [['followingId', 'IsFollowing']],
          as: 'following',
          required: false // to get left join
        }
      ]
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多