使用 knex.js 查询多个表

query multiple tables with knex.js

我想用 Expres.jsknex.js 渲染两个 tables,只使用一个 get 函数,以便使用来自两个 tables 的数据一个 HTML 模板。当我只查询一个 table(学校或学生)但我不知道如何处理两个 table 时,它会起作用。 有什么建议吗?

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

需要在一些reference key的基础上使用join才能使用多个table 这是使用参考键

连接两个 table 的 example

table 1:用户 和 table2:帐户

参考键是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');
})

希望这能给你更好的主意。

有关更多参考,请参阅 Docs

我找到了解决问题的方法并且它正在工作,只需将一个新查询添加到前一个查询的 .then 并将其作为参数传递,这样我就可以将两个表呈现为相同的 .html 并独立使用它们。

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

你的方法确实有效,但我建议你使用这个成语以避免 promise hell(请参阅 link 以获得更好的示例。)

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