如何使用以下和关注者示例在sequelize中连接两个单个表

时间:2017-09-10 18:59:58

标签: mysql node.js sequelize.js

此代码运行正常。我现在可以得到追随者和追随者我需要看到我得到的追随者是我也跟着他们?

这是一个问题,我如何向Followers表创建另一个查询/子查看,并看到我也跟随我的粉丝。

追随者表

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 

仍然在续集中苦苦挣扎。

1 个答案:

答案 0 :(得分:0)

将您的行查询转换为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
    }
  ]
});