javascript - How do I do a nested insert in Bookshelf.js - Stack Overflow

How do I insert an object like this into two tables Book and Pagevar book = {name: 'Hello',au

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
    }]
};

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
    }]
};
Share Improve this question asked Sep 17, 2014 at 7:36 BalanarayananBalanarayanan 4911 gold badge5 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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
    });

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

It will be something sort of like this:

return Promise.map(pages, (page) => book.related('pages').create(page));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745141061a4613432.html

相关推荐

  • javascript - How do I do a nested insert in Bookshelf.js - Stack Overflow

    How do I insert an object like this into two tables Book and Pagevar book = {name: 'Hello',au

    1小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信