0

Hi guys I'm trying to seed my data with knex and knex cli

I have 2 models: User & User Profile

User

CREATE TABLE users(
        id SERIAL PRIMARY KEY NOT NULL,
        name TEXT,
        screenname TEXT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      )

User Profile

CREATE TABLE userProfile(
        email TEXT,
        password TEXT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        user_id INTEGER,
        PRIMARY KEY (user_id),
        FOREIGN KEY (user_id) REFERENCES users (id)
      )

Note that user Profile points to User and its 1:1 relationship

Os I'm trying to insert my users and along with that, to insert their profile data

I have created seed file like this:

exports.seed = function(knex) {
  // Deletes ALL existing entries
  return knex('users').del()
    .then(function () {
      return knex('userprofile').del();
    })
    .then(() => {
      return knex('authenticationproviders').del();
    })
    .then(function () {
      return knex('users')
        .insert([
          { 
              name: 'john',
              screenname: 'admin' 
          },
          { 
              name: 'stephan',
              screenname: 'maras' 
          },
      ])
    })
    .then(function (users) {
         // here insert profile info about user
        // but user param doesn't contain userIds that are created 
    })
};

Here is how my profiles array looks:

[{
           email: 'test@gmail.com',
           user_id: 1, // this should be from existing user 
           password: 'pass1'
        },
        {
          email: 'test2@gmail.com',
          user_id: 2, // this should be from existing user that was created
          password: 'pass2'
       }]

Is there anyway how can I get userId from existing user, since users param is does not contain array of created users ??

Loki
  • 1,064
  • 2
  • 26
  • 55

0 Answers0