简体   繁体   English

如何在续集中获取模型的所有用户名

[英]How to get all username of model in sequelize

I am developing a web app with Docker using Express and Javascript .我正在使用ExpressJavascript使用Docker开发 Web 应用程序。 I am using a Three-layered architecture and using Sequelize to send queries using Mysql .我正在使用三层架构并使用Sequelize使用Mysql发送查询。 I have blogpost as a resource which has a relation to the accounts table.我有博客文章作为与帐户表有关系的资源。 This is how the relation looks like:这是关系的样子:

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})

This is how I retrieve all blogposts in the presentation layer :这就是我在表示层中检索所有博客文章的方式:

 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 })
        }
    })
})

And this is how the model looks like:这就是模型的样子:

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
  },

Now I want to retrieve the usernames with the userids.现在我想用用户 ID 检索用户名。 I have a working function that retrieves the a username by userid but I do not know how I can use that to get all the usernames from the userids.我有一个可以通过 userid 检索用户名的工作函数,但我不知道如何使用它从 userid 中获取所有用户名。 Any ideas how to solve this?任何想法如何解决这个问题?

Thanks in advance!提前致谢!

you can use the include option while querying blogposts , like this您可以在查询blogposts使用include选项,如下所示

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

it will use the join query to fetch the account but if you want use a separate query then you can also do something like this它将使用 join 查询来获取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 })
                    });
        }
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM