Wednesday, 31 July 2019

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.



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

No comments:

Post a Comment