简体   繁体   English

如何使用Knex.js和Bookshelf.js(ExpressJS / Postgress)插入一对多

[英]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 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 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 knex迁移文件

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. 因此,在这种情况下,我想要做的是插入teamNameteam_master与插入到新创建的唯一的用户ID表owner_idteam_master表。

Can someone point me in the right direction around this? 有人能指出我在这个方向的正确方向吗? Thank you. 谢谢。

You should be able to use the generated ID from the saved User to populate the Team, like this: 您应该能够使用已保存用户中生成的ID来填充团队,如下所示:

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
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM