BaconJuice
BaconJuice

Reputation: 3769

How to insert one to many with Knex.js and Bookshelf.js (ExpressJS/Postgress)

I'm trying to create a record on two tables when a user registers.

user.js

const db = require('../database');

const User = db.Model.extend({
  tableName: 'login_user',
  hasSecurePassword: true,
  hasTimestamps: true,
  team : () =>{
    return this.hasMany('Team', 'owner_id');
  }
});

module.exports = User;

team.js

const db = require('../database');

const Team = db.Model.extend({
  tableName: 'team_master',
  hasTimestamps: true,
  user: () => {
    return this.belongsTo('User', 'owner_id');
  },
});

module.exports = Team;

knex migration file

exports.up = function (knex, Promise) {
  return knex.schema.createTable('login_user', t => {
    t.increments('id').unsigned().primary();
    t.string('email').notNull();
    t.string('password_digest').notNull();
    t.string('fName').notNull();
    t.string('lName').notNull();
    t.timestamp('created_at').defaultTo(knex.fn.now())
    t.timestamp('updated_at').defaultTo(knex.fn.now())
  })
  .createTable('team_master', t => {
    t.increments('id').unsigned().primary();
    t.integer('owner_id').references('id').inTable('login_user');
    t.string('teamName').notNull();
    t.timestamp('created_at').defaultTo(knex.fn.now())
    t.timestamp('updated_at').defaultTo(knex.fn.now())
  });
};

exports.down = function (knex, Promise) {
  return knex.schema.dropTable('login_user').dropTable('team_master');
};

My insert code looks like the following

const user = new User({
    email: req.body.email,
    password: req.body.password,
    fName: req.body.fName,
    lName: req.body.fName,
    //teamName: req.body.teamName,
  });

  user.save().then(() => {
    res.send('User Created');
  });

So in this case what I want to do is insert teamName into the team_master table with the newly created unique user ID inserted into the owner_id in team_master table.

Can someone point me in the right direction around this? Thank you.

Upvotes: 3

Views: 955

Answers (1)

Nick Gagne
Nick Gagne

Reputation: 130

You should be able to use the generated ID from the saved User to populate the Team, like this:

user.save()
  .then(user => {
    // user.id should be populated with the generated ID

    return new Team({
      owner_id: user.id,
      // set your other team properties
    }).save()
  })
  .then(team => {
    // do something with team
  })

Upvotes: 2

Related Questions