Skip to content
Advertisement

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

I have 2 tables with class and subjects.

  • class(id,name,student_count)
  • subjects(id,name,class_id)

I want to populate class_id with name,student_count, and id on the select query. How do I do this using SQL or Knex?

I tried using join, but I get only one field not all fields in a row.

The expected result would be:

By the way, answer in Knex or plain SQL would help!

Advertisement

Answer

You have to either use an inner join or a left join.

In SQL it would look something like this:

In Knex it looks something like this:

You will get an object with the variable names after AS as field names. To get it into the format you want you have to create a mapper function:

Which is, for example, called used like this:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement