【问题标题】:sequelize. Find all posts and add column "isLiked" from table "likes" with boolean value if current user marked this post with 'like'续集。如果当前用户将此帖子标记为“喜欢”,则查找所有帖子并使用布尔值从表“喜欢”中添加列“isLiked”
【发布时间】:2022-07-27 12:55:01
【问题描述】:

我有两种型号:

const Users = sequelize.define('users', {
    id: { type: DataTypes.INTEGER, primaryKey: true, unique: true, allowNull: false },
    name: { type: DataTypes.STRING, allowNull: false },
    role: {
        type: DataTypes.STRING,
        values: [
            'student',
            'headman',
            'admin'
        ],
        defaultValue: 'student',
        allowNull: false
    },
    avatarImage: {
        type: DataTypes.TEXT,
        allowNull: false
    }
})

const Posts = sequelize.define('posts', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    title: { type: DataTypes.STRING, allowNull: false },
    content: { type: DataTypes.TEXT, allowNull: false },
    deadline: { type: DataTypes.DATE, allowNull: false },
    postType: {
        type: DataTypes.STRING,
        values: [
            'homework',
            'news',
        ],
        defaultValue: 'news', allowNull: false
    }
})

通过模型喜欢

受到多对多关系的约束

const Likes = sequelize.define('likes', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    postType: {
        type: DataTypes.STRING,
        values: [
            'homework',
            'news',
        ],
        allowNull: false
    }

})

//relations 
Users.belongsToMany(Posts, {
    through: { model: Likes, unique: false },
    as: "postsLiked",
    foreignKey: "userId",
});
Posts.belongsToMany(Users, {
    through: { model: Likes, unique: false },
    as: "usersLiked",
    foreignKey: "postId",
});

所以,我想获取所有帖子,每个帖子都带有附加列“isLiked”,并带有布尔值(true,如果提出请求的用户将此帖子标记为“like”。以其他方式 - 假)。我不需要所有喜欢这篇文章的用户列表,只需检查一个即可。

所以,我的控制器中有这个查询

async getAll(req, res) {
  let homeworks = await Posts.findAll({
          where: {
              postType: 'homework'
          },
          include: [
              {
                  model: Subjects,
                  as: 'subject',
                  attributes: ['id', 'title', 'fullName']
              },
              {
                  model: Users,
                  as: 'usersLiked',
                  //here i get list of all users likes this post
                  //if i add propery where (where:{id: user.id}), i get only posts liked by my user
s                    }
          ],

      })
}
        

那么,你能帮我解决这个问题吗?

//here is the response i have now
//current user.id is 1

{
    "id": 2,
    "title": "Post 2",
    ...post fields ...
    "subject": {...},
    "usersLiked": [
        {
            "id": 1,
            "name": "Max Sobolev",
        },
        {
            "id": 2,
            "name": "Albert Cooper",
        }
    ]
},

//what i want to see

{
    "id": 2,
    "title": "Post 2",
    ...post fields ...
    "subject": {...},
    "isLiked": true
},

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    更新 13.04: 所以,我找到了如何获取所有带有“where”属性的帖子: 我只需要使用require: falsepropery

    homeworks = await Posts.findAll({
      where: {
          postType: 'homework',
          deadline: {
              [Op.gte]: moment()
          }
      },
      include: [
          {
              model: Subjects,
              as: 'subject',
              attributes: ['id', 'title', 'fullName']
          },
          {
              model: Users,
              as: 'usersLiked',
              where: {
                  id: req.user.id,
              },
              required: false, // <--- and now i get all posts with empty array 'userLiked' if current user didn't liked this post
          }
      ],
    
    
    })

    【讨论】:

      【解决方案2】:

      您可以使用此方法获取 isLiked 字段,如果用户喜欢该帖子,则该字段为 true,否则为 false

      const gender = await db.SubProduct.findAll(userId && {
        attributes: {
          include: [
            [Sequelize.cast(Sequelize.where(Sequelize.col("likes.userId"), userId), "boolean"), "isLiked"]
          ],
      
        },
        include: [
          { model: db.Like, as: "likes", attributes: [], required: false },
      
        ],
        group: ['SubProduct.id', 'likes.id']
      });
      

      【讨论】:

        猜你喜欢
        • 2022-01-16
        • 2020-11-04
        • 2018-07-27
        • 2017-10-07
        • 2020-07-13
        • 1970-01-01
        • 2020-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多