如何获得后继模型的所有用户名

问题描述 投票:2回答:1

我正在使用ExpressJavascriptDocker开发一个Web应用程序。我正在使用三层体系结构,并使用Sequelize使用Mysql发送查询。我有blogpost作为与accounts表有关系的资源。关系是这样的:

const Account = sequelize.define('accounts', {
    personId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    username: {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true
    },
    email: {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true
    },
    userPassword: Sequelize.TEXT
}, {
    timestamps: false
})

const Blogpost = sequelize.define('blogposts', {
    blogId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    title: Sequelize.TEXT,
    content: Sequelize.TEXT,
    posted: Sequelize.TEXT,
    imageFile: Sequelize.TEXT
}, {
    timestamps: false
})
Blogpost.belongsTo(Account, {foreignKey: "userId", foreignKeyConstraint: true})

这是我在表示层中检索所有博客文章的方式:

 router.get("/", function(request, response){

    blogManager.getAllBlogposts(function(errors, blogposts){
        if(errors.includes("databaseError")){
            response.send("<h1>Something went wrong!</h1>")
        }
        else if(errors.length > 0){
            const model = {
                errors
            }
            console.log("blogpostsModel:", { model })
            response.render("blogposts.hbs", { model })
        }else{
            const model = {
                blogposts
            }
            response.render("blogposts.hbs", { model })
        }
    })
})

这就是model的样子:

blogposts {
    dataValues: {
        blogId: 2,
        title: 'fsdhkjfsdahflhs',
        content: 'fhjkdsfkbmngfhyuxgc',
        posted: '275760-07-09',
        imageFile: 'module-6.jpg',
        userId: 1
    },
 _previousDataValues: {
      blogId: 2,
      title: 'fsdhkjfsdahflhs',
      content: 'fhjkdsfkbmngfhyuxgc',
      posted: '275760-07-09',
      imageFile: 'module-6.jpg',
      userId: 1
  },

  blogposts {
      dataValues: {
          blogId: 3,
          title: 'fjhhkjfsa',
          content: 'gfhjdsakdasdsa',
          posted: '8989-08-09',
          imageFile: 'module-6.jpg',
          userId: 2
  },
 _previousDataValues: {
     blogId: 3,
     title: 'fjhhkjfsa',
     content: 'gfhjdsakdasdsa',
     posted: '8989-08-09',
     imageFile: 'module-6.jpg',
     userId: 2
  },

现在,我想使用用户名检索用户名。我有一个可以通过用户ID检索用户名的工作函数,但是我不知道如何使用该函数从用户ID中获取所有用户名。任何想法如何解决这个问题?

提前感谢!

javascript express sequelize.js
1个回答
0
投票

您可以像这样查询include时使用blogposts选项

Blogpost.findAll({
    include: [{
        model:Account,
    }]
});

它将使用连接查询来获取account,但是如果您想使用单独的查询,那么您也可以执行以下操作

router.get("/", function(request, response){

    blogManager.getAllBlogposts(function(errors, blogposts){
        if(errors.includes("databaseError")){
            response.send("<h1>Something went wrong!</h1>")
        }
        else if(errors.length > 0){
            const model = {
                errors
            }
            console.log("blogpostsModel:", { model })
            response.render("blogposts.hbs", { model })
        }else{
            const userIds = blogposts.map(blogpost => 
                                            blogpost.userId);
            // query the Account with the userIds;
            Account.find({ where : { userId : userIds}})
                   .then((accounts) => {
                      const blogpostsWithUserNames = 
                              blogposts.map(blogpost => {
                                 const findAccount = 
                                    accounts.filter(acc => 
                                     acc.userId === blogpost.userId);
                                 return { 
                                    ...blogpost, 
                                    userName : findAccount.username,
                                 }
                              })
                      const model = { 
                           blogposts : blogpostsWithUserNames
                      }
                      response.render("blogposts.hbs", 
                                   { model })
                    });
        }
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.