简体   繁体   English

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

[英]How do I do a nested insert in Bookshelf.js

How do I insert an object like this into two tables Book and Page 如何将这样的对象插入两个表Book和Page

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

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.org/#Collection-instance-create 以下是书架文档中最清洁方式的链接: http//bookshelfjs.org/#Collection-instance-create

It will be something sort of like this: 它会是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM