query multiple tables with knex.js

允我心安 提交于 2019-12-06 14:59:45

your approach indeed works, however i suggest you this idiom in order to avoid the promise hell (see the link for even better examples.)

router.get("/schools",function(req,res){
  var schools
  knex("schools").select().then(function(ret){
    schools=ret
    return knex("students").select()
  }).then(function(students){
    res.render("schools",{
      students: students,
      schools: schools
    })
  })
})

You need to use join to use multiple tables on the basis of some reference key Here is example of join two tables at with reference key

table 1:users And table2: accounts

And reference key is user's primary key

.then(function() {
  return knex('users')
    .join('accounts', 'users.id', 'accounts.user_id')
    .select('users.user_name as user', 'accounts.account_name as account');
})

Hope this can give you better idea.

For more reference see the Docs

I found the solution, to the problem and it is working, just adding a new query to the .then of the previous one and passing it as an argument so I can render both tables to the same .html and use them independently.

    knex.select()
    .from('schools')
    .then(function(schools){
        knex.select()
        .from('students')
        .then(function(students) {
            res.render('schools', {
                students: students,
                schools: schools
            });
        });
    }).catch(function(error) {
        console.log(error);
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!