Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a nested insert in Bookshelf.js

How do I insert an object like this into two tables Book and Page

var book = {
    name: 'Hello',
    author: 'World',
    pages: [{
        pagetitle: 'intro',
        book: 8
    }, {
        pagetitle: 'chaptessr1',
        book: 8
    }]
};
like image 411
Balanarayanan Avatar asked Sep 17 '14 07:09

Balanarayanan


2 Answers

I think you are probably looking for some sort of shortcut, but don't think there is one:

var Promise = require('bluebird');
var Book = bookshelf.Model.extend({
    tableName: 'books'
});
var Page = bookshelf.Model.extend({
    tableName: 'pages'
});
var Pages = bookshelf.Collection.extend({
    model: Page
});

Book.forge({name: 'Hello', author: 'World'}).save()
    .then(function(book) {
        var pages = Pages.forge([
            {pagetitle: 'intro', book: book.id},
            {pagetitle: 'chatessr1', book: book.id}
        ]);

        return pages.invokeThen('save', null);
    }).then(function(){
        // now all the pages and the book should be saved
    });
like image 137
Allie Hoch Janoch Avatar answered Sep 29 '22 21:09

Allie Hoch Janoch


Here is the link to the cleanest way, in the bookshelf docs: http://bookshelfjs.org/#Collection-instance-create

It will be something sort of like this:

return Promise.map(pages, (page) => book.related('pages').create(page));
like image 25
Greg Norris Avatar answered Sep 29 '22 21:09

Greg Norris