Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在sequelize中获取模型的所有用户名_Javascript_Express_Sequelize.js - Fatal编程技术网

Javascript 如何在sequelize中获取模型的所有用户名

Javascript 如何在sequelize中获取模型的所有用户名,javascript,express,sequelize.js,Javascript,Express,Sequelize.js,我正在使用Express和Javascript开发一个带有Docker的web应用程序。我使用的是三层架构,并使用Sequelize使用Mysql发送查询。我有blogpost作为一种与accounts表相关的资源。这是关系的样子: const Account = sequelize.define('accounts', { personId: { type: Sequelize.INTEGER, allowNull: false, pri

我正在使用ExpressJavascript开发一个带有Docker的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})
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
  },
这就是我在表示层中检索所有博客帖子的方式:

 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 })
        }
    })
})
现在我想用用户名检索用户名。我有一个通过userid检索用户名的工作函数,但我不知道如何使用该函数从userid获取所有用户名。有什么办法解决这个问题吗


提前谢谢

您可以在查询
博客帖子时使用
包含
选项,如下所示

Blogpost.findAll({
    include: [{
        model:Account,
    }]
});
它将使用join查询来获取
帐户
,但是如果您想使用单独的查询,那么您也可以这样做

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 })
                    });
        }
    })
})
router.get(“/”,函数(请求、响应){
getAllBlogposts(函数(错误,blogposts){
if(errors.includes(“databaseError”)){
response.send(“出错了!”)
}
否则如果(errors.length>0){
常数模型={
错误
}
log(“blogpostsModel:,{model}”)
response.render(“blogposts.hbs”,{model})
}否则{
const userIds=blogposts.map(blogpost=>
blogpost.userId);
//使用用户名查询账户;
Account.find({where:{userId:userIds}})
。然后((账户)=>{
常量blogpostsWithUserNames=
blogpost.map(blogpost=>{
常量findAccount=
accounts.filter(acc=>
acc.userId==blogpost.userId);
返回{
…博客帖子,
用户名:findAccount.userName,
}
})
常量模型={
blogposts:BlogPostSwithUserName
}
response.render(“blogposts.hbs”,
{model})
});
}
})
})