bookshelfjs 笔记

bookshelf,连接sql数据库的orm,使用knex生成查询串

where(filter)的filter参数除了可以{id}这样的obj,还可以用q=>{ q.whereIn('id', ids); }这样的func,q是knex中的queryBuilder。

fetch(options)的options参数中{ withRelated: [xxx] }可以预取关联的model数据。

比如一对多关系

一Book有多Page,一Page属于一Book

(Book)上可以定义获取(Page)的函数:

1
pages() { return this.hasMany(Page, 'pageId'); }

然后fetch时提供withRelated:来预取:

1
const book = await Book.fetch({ withRelated: ['pages']});

之后用book.related('pages')访问这个预取的model

(Page)上可以定义获取(Book)的函数:

1
book() { return this.belongsTo(Book, 'bookId'); }

然后fetch时提供withRelated:来预取:

1
const page = await Page.fetch({ withRelated: ['book'] });

之后用page.related('book')访问这个预取的model

比如多对多关系

一Buyer买多Item,一Item被多Buyer买

(如 Buyer)上可以定义获取(如 Item)的函数:

1
2
3
4
5
items() {
return this.belongsToMany(Item)
.through(BuyerItem, 'buyerId', 'itemId')
.withPivot(['buyCount']);
}

(注:使用.through()时,中间表BuyerItem要有id域)

然后fetch时提供withRelated:来预取:

1
const buyer = await Buyer.fetch({ withRelated: ['items'] });

之后用buyer.related('items')访问这个预取的model

buyer的关联items没有预取时,直接取items:

1
await buyer.load(['items']);

保存时自动hash密码

initialize中注册回调函数:

1
2
3
4
initialize() {
bookshelf.Model.prototype.initialize.call(this);
this.on('saving', util.hashPasswordWithBcrypt);
}

使用事务

1
2
3
4
5
6
7
bookshelf.transaction(await transacting => {
...
await xxx.fetch(xxx, { transacting });
await xxx.save(xxx, { transacting });
await xxx.destroy({ transacting });
...
}

参考