简体   繁体   中英

How to set up my database model in bookshelf.js

After using knex to handle all of my database needs, I've been looking at bookshelf.js to set up models and get a bit more structure.

I tried it out with a simple demo.

user (table)

  • id (increments)
  • name (string)

task (table)

  • id (increments)
  • description (string)
  • created_by (integer).references('user.id')
  • assigned_to (integer).references('user.id')

I then define my models like this.

var User = bookshelf.Model.extend({
    tableName: 'user',
    assigned_tasks: function(){
        return this.hasMany(Task, ['assigned_to']);
    },
    created_tasks: function(){
        return this.hasMany(Task, ['created_by']);
    }
})

var Task = bookshelf.Model.extend({
    tableName: 'task',
    created_by_user: function(){
        return this.belongsTo(User, ['created_by'], ['id']);
    },
    assigned_to_user: function(){
        return this.belongsTo(User, ['assigned_to'], ['id']);
    }
})

When I run the following function, I get the response I want.

function getAllUsers(){
    new User().fetchAll({withRelated: ['assigned_tasks', 'created_tasks']}).then(function(result){
        var data = result.toJSON();
        data.forEach(function(user){
            console.log(user);
        })
    })
}

I get an array of all the users, which then contains an array of the tasks assigned to that user, and an array of the tasks created by that user.

But when I run the following function

function getAllTasks(){
    new Task().fetchAll({withRelated: ['assigned_to_user', 'created_by_user']}).then(function(result){
        var data = result.toJSON();
        data.forEach(function(task){
            console.log(task);
        })
    })
}

I get the tasks, but the fields assigned_to_user and created_by_user are just empty Objects.

{ id: 1,
  description: 'Ta på folk',
  project_id: '1',
  priority: 2,
  start_date: null,
  due_date: null,
  end_date: null,
  status: 1,
  created_by: 1,
  assigned_to: 2,
  created_at: null,
  updated_at: null,
  assigned_to_user: {},
  created_by_user: {} }

Is there something I'm not getting here? Shouldn't the task contain an Object with the user that is referenced?

Thanks

So I figured this out. Seems like my syntax was the only thing that was wrong.

So when doing this:

var Task = bookshelf.Model.extend({
    tableName: 'task',
    created_by: function(){
        return this.belongsTo(User, 'created_by');
    },
    assigned_to: function(){
        return this.belongsTo(User, 'assigned_to');
    }
})

My task was returned with the created_by and assigned_to objects populated with the information.

{ id: 1,
  description: 'Ta på folk',
  project_id: '1',
  priority: 2,
  start_date: null,
  due_date: null,
  end_date: null,
  status: 1,
  created_by:
   { id: 1,
     name: 'Stian Bakken',
     slack_name: 'stiba',
     slack_id: 'RU233UR',
     nickname: 'the dog',
     created_at: null,
     updated_at: null },
  assigned_to:
   { id: 2,
     name: 'Thomas Feit',
     slack_name: 'thraxx',
     slack_id: 'RJKJK42',
     nickname: 'The cave',
     created_at: null,
     updated_at: null },
  created_at: null,
  updated_at: null }

I also figured out another thing when it comes to fetching multiple dimensions of relations.

function getAllUsers(){
    new User().fetchAll({withRelated: ['assigned_tasks', 'created_tasks', 'assigned_tasks.assigned_to', 'assigned_tasks.created_by', 'created_tasks.assigned_to', 'created_tasks.created_by']}).then(function(result){
        var data = result.toJSON();
        data.forEach(function(user){
            console.log(user);
            user.assigned_tasks.forEach(function(task){
                console.log(task);
            })
        })
    })
}

Returns the following result:

{ id: 1,
  name: 'Stian Bakken',
  slack_name: 'stiba',
  slack_id: 'RU233UR',
  nickname: 'the dog',
  created_at: null,
  updated_at: null,
  assigned_tasks: [],
  created_tasks:
   [ { id: 1,
       description: 'Ta på folk',
       project_id: '1',
       priority: 2,
       start_date: null,
       due_date: null,
       end_date: null,
       status: 1,
       created_by: [Object],
       assigned_to: [Object],
       created_at: null,
       updated_at: null } ] }

So, it then populates the individual tasks inside the user object with the user-information from the user that created the task and the one the task is assigned to. I hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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