使用knex.js查询多个表

kar*_*tto 1 javascript mysql node.js express knex.js

我想使用Expres.jsknex.js两个表进行渲染,只使用一个get函数,以便在一个HTML模板中使用两个表中的数据.当我只查询一个表(学校或学生)但我不知道如何处理两个表时,它可以工作.有什么建议吗?

app.get('/schools', function(req, res) {

    knex.select()
    .from('schools', 'students')
    .then(function(schools, students) {
        res.render('schools', {
            schools: schools,
            students: students
        });
    }).catch(function(error) {
        console.log(error);
    });
});
Run Code Online (Sandbox Code Playgroud)

Som*_*iks 6

你的方法确实有效,但是我建议你使用这个习语,以避免承诺地狱(请参阅链接以获取更好的示例。)

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
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

  • 这很糟糕,因为您要多次重新访问数据库。请改用加入。 (2认同)

abd*_*rik 5

您需要使用join基于某些表来使用多个表reference key 这里是example使用引用键连接两个表

表1:用户和表2:帐户

而参考键是 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');
})
Run Code Online (Sandbox Code Playgroud)

希望这可以给你更好的主意.

有关更多参考,请参阅文档