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 | items() { |
(注:使用.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 | initialize() { |
使用事务
1 | bookshelf.transaction(await transacting => { |