Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  124] [ 1]  / answers: 1 / hits: 6605  / 4 Years ago, wed, april 8, 2020, 12:00:00

I have this many to many relation in 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
})
}


I need to show a student's enrolled courses.
How do I query (all/an array of) courses by student.id?



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx



Stack: TypeScript, [email protected], Postgres@12-alpine, [email protected]


More From » sql

 Answers
1
const coursesOfSingleStudent = await knex('courses').whereIn('id',
knex('student_courses').select('course_id').where('student_id', studentId)
)


Though you might be better off using objection.js which allows you to declare relation mappings and then query directly:



const studentWithCourses = await Student.query().findById(studentId).withGraphFetched('courses');

[#4233] Sunday, April 5, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deving

Total Points: 26
Total Questions: 94
Total Answers: 103

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;