如何在 select 查询中使用数据而不是仅使用外键 ID 填充外键字段?

How do I populate a foreign key field with data instead of just foreign key id on select query?

我有 2 个表 class 和主题。

我想在 select 查询中使用名称student_count 和 ID 填充 class_id。如何使用 SQL 或 Knex 执行此操作?

我尝试使用连接,但我只得到一个字段,而不是一行中的所有字段。

预期结果为:

subject{
   name: "data"
   id: "data"
   class: {
     id: "data"
     name: "data"
     student_count: "data"
  }
}

顺便说一下,用 Knex 或普通 SQL 回答会有帮助!

您必须使用内连接或左连接。

在 SQL 中看起来像这样:

SELECT
      s.id            AS subject_id
    , s.name          AS subject_name
    , c.id            AS class_id
    , c.name          AS class_name
    , c.student_count AS class_student_count
FROM subjects s
INNER JOIN class ON s.class_id = c.id
WHERE s.id = 1

在 Knex 中它看起来像这样:

getOne: () => knex
    .select(   's.id AS subject_id'
             , 's.name AS subject_name'
             , 'c.id AS class_id'
             , 'c.name AS class_name'
             , 'c.student_count AS class_student_count'
           )
    .from('subjects AS s')
    .innerJoin('class AS c', 's.class_id', 'c.id')
    .where('s.id': 1)

你会得到一个以AS后面的变量名作为字段名的对象。要将其转换为您想要的格式,您必须创建一个映射器函数:

function mapToWantedFormat(subject) {
  return {
    name: subject.subject_name,
    id: subject.subject_id
    class: {
      id: subject.class_id,
      name: subject.class_name,
      student_count: subject.class_student_count
    }
  };
};

例如,它的用法是这样的:

module.exports.getOne = async (req, res, next) => {
  try {
    const subject = await getOne();
    if (subject) {
      res.status(200).json(mapToWantedFormat(subject));
    } else {
      res.status(404).json();
    }
  } catch (error) {
    next(error);
  }
};