Used json_agg
Session table with two foreign keys at users and devices
exports.up = async function (knex) {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
return knex.schema.createTable('sessions', function (table) {
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()'));
table
.integer('user')
.notNullable()
.references('id')
.inTable('users')
.onDelete('cascade');
table
.integer('device')
.notNullable()
.references('id')
.inTable('devices')
.onDelete('cascade');
table.timestamp('session_start').defaultTo(knex.raw('CURRENT_TIMESTAMP'));
table.timestamp('session_pre_end').nullable();
});
};
Knex : get nested data using join
await this.knex
.from('sessions')
.join('users', 'sessions.user', 'users.id')
.groupBy(['sessions.id'])
.join('devices', 'sessions.device', 'devices.id')
.select(
this.knex.raw(
`sessions.id, json_agg(users) as users, json_agg(devices) as devices`,
),
);
Output JSON
{
"sessions": [
{
"id": "881e4a2c-4e55-4045-b80d-3232ab3b616a",
"users": [
{
"id": 2,
"access_type": "user",
"firstname": "Two",
"lastname": "Karki",
"phone": "9845225544",
"email": "example2@nest.it",
"password": "123456"
}
],
"devices": [
{
"id": 1,
"short_name": "ps1",
"full_name": "Play Station 5 - 1",
"model_number": "ps5001",
"type": "console",
"isActive": true,
"created_at": "2023-01-31T00:17:16.974896+05:45",
"updated_at": "2023-01-31T00:17:16.974896+05:45"
}
]
}
]
}