Skip to content

Instantly share code, notes, and snippets.

View tgriesser's full-sized avatar

Tim Griesser tgriesser

View GitHub Profile
bookshelf.Model.find = function(id, options) {
var model = new this();
model.set(this.idAttribute, id);
return model.fetch(options);
};
var Customer = bookshelf.Model.extend({
account: function() {
return this.belongsTo(Account);
},
});
Customer.forge({id: 1}).fetch().then(function(customer) {
console.log(customer.toJSON());
// In Usage:
// ----
var User = Bookshelf.Model.extend({
posts: function() {
return this.hasMany(Post);
}
});
@tgriesser
tgriesser / 01.coffee
Last active August 29, 2015 14:01 — forked from w33ble/01.coffee
# bookshelf code, to compliment the knex code above
exports.PG = Bookshelf.PG = Bookshelf.initialize
client: 'pg'
connection: config.get('/postgres')
# property photo model
exports.PropertyPhoto = PropertyPhoto = Bookshelf.PG.Model.extend
tableName: 'property_photos'
var Bookshelf = require('bookshelf');
var DB = Bookshelf.initialize({
client: 'sqlite3',
connection: {
filename: ':memory:'
}
});
var Parent = Bookshelf.Model.extend({
tableName: 'parent',
child: function() {
return this.hasOne(Child);
}
});
var Child = Bookshelf.Model.extend({
tableName: 'child',
//this has an attribute parent_id
_.each(['hasMany', 'hasOne', 'belongsToMany', 'morphOne', 'morphMany', 'belongsTo', 'through'], function(method) {
var original = Model.prototype[method]
Model.prototype[method] = function() {
// Stuff here
return original.apply(this, ...)
};
});
// Note: you don't need to use when.js, any good promise library will do (Q.js also would work)
var when = require('when');
// Deleting all models in a collection at once:
when.all(collection.invoke('destroy'))).then(function() {
collection.reset();
// ...
});
// Saving all models in collection at once:
test("add with parse and merge", function() {
var Model = Backbone.Model.extend({
parse: function (data) {
return data.model;
}
});
var collection = new Backbone.Collection();
collection.model = Model;
collection.add({id: 1});
})(function(KNEX) {
// Dependencies, ordered most to least likely to be manually injected...
// this only applies for CommonJS style require, since AMD config can account for this otherwise.
var deps = ['underscore', 'when', './clients/base', './clients/mysql', './clients/postgres', './clients/sqlite3'];
var root = this;
var slice = [].slice;
var Initialize = function() {