如何在Bookshelf.js中执行嵌套插入

时间:2014-09-17 07:36:04

标签: javascript bookshelf.js

如何将这样的对象插入两个表Book and Page

var book = {
    name: 'Hello',
    author: 'World',
    pages: [{
        pagetitle: 'intro',
        book: 8
    }, {
        pagetitle: 'chaptessr1',
        book: 8
    }]
};

2 个答案:

答案 0 :(得分:4)

我认为你可能正在寻找某种捷径,但不要认为有一种捷径:

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

答案 1 :(得分:1)

这是书架文档中最干净方式的链接: http://bookshelfjs.org/#Collection-instance-create

这将是这样的:

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