如何查询Knex.js的多对多关系?
How to query many to many relations with Knex.js?
我在 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
})
}
我需要显示学生已注册的课程。
如何通过 student.id
查询 courses
的(all/an 数组)?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
堆栈:打字稿,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');
我在 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
})
}
我需要显示学生已注册的课程。
如何通过 student.id
查询 courses
的(all/an 数组)?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
堆栈:打字稿,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');