我在 Postgres 中有这样的多对多关系:
// migrations/2020_create_initial_tables.js
exports.up = function(knex) {
return knex.schema
.createTable('students', function(table) {
table.increments('id').primary()
table
.string('email')
.unique()
.index()
table.string('password')
})
.createTable('courses', function(table) {
table.increments('id').primary()
table.string('title').notNullable()
table.text('description')
})
// A student can enroll many courses
// A course can have many students
.createTable('student_courses', function(table) {
table.increments('id').primary()
table
.integer('student_id')
.references('id')
.inTable('students')
table
.integer('course_id')
.references('id')
.inTable('courses')
})
.catch(err => {
console.error(err)
throw err
})
// .finally(() => knex.destroy());
}
exports.down = function(knex) {
return knex.schema
.dropTableIfExists('students')
.dropTableIfExists('courses')
.dropTableIfExists('student_courses')
.catch(err => {
console.error(err)
throw err
})
}
我需要显示学生注册的类(class)。
如何通过 student.id
查询(全部/一组)类(class)
?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
堆栈:TypeScript、knex@v0.20.12、Postgres@12-alpine、pg@v7.18.2
最佳答案
const coursesOfSingleStudent = await knex('courses').whereIn('id',
knex('student_courses').select('course_id').where('student_id', studentId)
)
尽管您最好使用 objection.js,它允许您声明关系映射,然后直接查询:
const studentWithCourses = await Student.query().findById(studentId).withGraphFetched('courses');
关于javascript - 如何用 Knex.js 查询多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61092854/