Bookshelfjs - 更新相关集合

时间:2016-06-21 06:09:10

标签: bookshelf.js knex.js

如何更新相关集合 例如:,我有以下模型和集合

const Book = bookshelf.Model.extend({
    tableName: 'book',
    pages: function() {
        return this.hasMany(Page, 'book_id');
    }
});

const Page = bookshelf.Model.extend({
    tableName: 'page',
    idAttribute: 'page_id'
});

const Pages = bookshelf.Collection.extend({
    model: Page
});

function updateBook(){
    var book_id = 1;
    var book = {name: 'book1'};
    var pages = [{page_id: 1, book_id: 1, name: 'New Page 1'}, {page_id: 3, book_id: 1, name: 'Page 3'}];
    Book.forge({'book_id': book_id})
    .save(book)
    .then((newBook) => {
        /*
        **Here I want to update the pages of the book. **
        */
    });
}

需要以下列方式更新页面: 假设这本书最初有两页:

[{page_id: 1, book_id: 1, name: 'Page 1'}, {page_id: 2, book_id: 1, name: 'Page 2'}]}); 

我想:

  1. 将首页的名称修改为'新页面1'
  2. 删除第2页
  3. 添加新的第3页
  4. 我尝试了以下操作,但页面表中没有任何更改。

    newBook.load('pages')
        .then((newBook) =>{
            newBook.related('pages').reset(pages);
        })
    

0 个答案:

没有答案