用knex.js查询多个表 [英] query multiple tables with knex.js

查看:805
本文介绍了用knex.js查询多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to render with Expres.js and knex.js two tables using for that only one get function in order to use the data from both tables in one HTML template. It works when I query only one table (schools or students) but I don't know how to do with two tables. Any suggestion?

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

推荐答案

您的方法确实有效,但是我建议您使用这种习惯用法,以避免

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

这篇关于用knex.js查询多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆