2

What is the process for generating bookshelf Model objects from an existing MySQL database?

The examples on the Bookshelf.js site show several model objects...

var knex = require('knex')({client: 'mysql', connection: 
process.env.MYSQL_DATABASE_CONNECTION });
var bookshelf = require('bookshelf')(knex);

var User = bookshelf.Model.extend({
    tableName: 'users',
    posts: function() {
        return this.hasMany(Posts);
    }
});

The closest the Knex.js site comes to this is mentioning migrations. However, using their syntax...

$ npm install -g knex
$ npm install knex --save
$ npm install mysql --save
$ knex init
$ knex migrate:make knextest

... only generates one file with empty functions ...

exports.up = function(knex, Promise) {

};

exports.down = function(knex, Promise) {

};

... which makes sense, since knex is NOT the ORM. I guess I ended up here because Bookshelf didn't mention any tools for this.

On a side note, I've checked my knexfile.js and made sure it has a valid configuration:

development: {
  client: 'mysql',
  connection: {
    host : 'localhost',
    user : 'root',
    password : 'oogaboogs',
    database : 'knexdb'
  }
},

Is this not possible? It would really suck to create thousands of Model objects by hand for an existing database.

Thanks, in advance.

G. Deward
  • 1,542
  • 3
  • 17
  • 30
  • Maybe just write an automigrate function like similar to https://stackoverflow.com/a/31119634/6702495 – frozen Jul 25 '17 at 17:37

1 Answers1

0

You could use Yeoman-based generator-bookshelf.

Creating models is as simple as:

$ yo bookshelf:model
? Table Name users
? idAttribute id
? Add a relationship? No