【问题标题】:query multiple tables with knex.js使用 knex.js 查询多个表
【发布时间】:2017-01-30 13:42:12
【问题描述】:

我想用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);
    });
});

【问题讨论】:

    标签: javascript mysql node.js express knex.js


    【解决方案1】:

    您的方法确实有效,但我建议您使用此成语以避免promise hell(请参阅链接以获取更好的示例。)

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

    【讨论】:

    • 谢谢!它的工作方式与我发布的相同,但结构更好。
    • 这很糟糕,因为您要多次重新访问数据库。请改用 Join。
    【解决方案2】:

    我找到了问题的解决方案并且它正在工作,只需将新查询添加到前一个查询的 .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);
        });
    

    【讨论】:

      【解决方案3】:

      在一些reference key的基础上使用多个表需要使用join 这是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');
      })
      

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

      更多参考请参阅Docs

      【讨论】:

      • 感谢您的回答 adbulbarik,但使用 join 我将创建一个包含数据的表,但我想要的是呈现两个表。可能是我没有正确解释。幸运的是,我找到了可行的方法,我会发布它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多