【问题标题】:Knex/SQL: Merge one to many join in one objectKnex/SQL:在一个对象中合并一对多连接
【发布时间】:2020-01-15 04:15:32
【问题描述】:

我有两个表:“page”和“page_css”。我想要 page 和 page_css 之间的一对多关系(一页包含多个 page_css)。 见表结构:

页表结构:

Page_css 表结构:

这是我正在使用的 Knex 查询:

var page = knex('page')
  .where({ slug: req.params.slug })
  .join('page_css', { 'page_css.page_id': 'page.id' })
  .then(function(page) {
    if (page) {
      return res.json(page);
    }
    return res.send('page not found');
  });

这是我得到的结果:

但我想要这样的结果:

我需要运行什么 SQL/Knex 查询才能像上面的格式一样获得它?

【问题讨论】:

    标签: mysql sql node.js database knex.js


    【解决方案1】:

    Knex 不能变魔术,它“只是”构造正确 SQL 查询的查询构建器。

    您需要将此平面结果转换为您希望的对象。

    const flatData = [{
      id: 1,
      slug: 'test',
      page_id: 1,
      css_file: 'main'
    }, {
      id: 1,
      slug: 'test',
      page_id: 1,
      css_file: 'hero'
    }];
    
    const resultMap = flatData.reduce((result, row) => {
      result[row.id] = result[row.id] || {
        ...row,
        css_file: []
      };
    
      result[row.id].css_file.push(row.css_file);
    
      return result;
    }, {});
    
    console.log(Object.values(resultMap));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-09
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多