javascript – 获取Bookshelf.js模型时使用“new”的区别是什么?
作者:互联网
Bookshelf.js文档的代码示例包含“new”且没有“new”:
这里http://bookshelfjs.org/#Model-instance-hasMany
let Author = bookshelf.Model.extend({
tableName: 'authors',
books: function() {
return this.hasMany(Book);
}
});
// select * from `authors` where id = 1
// select * from `books` where author_id = 1
Author.where({id: 1}).fetch({withRelated: ['books']}).then(function(author) {
console.log(JSON.stringify(author.related('books')));
});
但这里是http://bookshelfjs.org/#Model-instance-fetch
let Book = bookshelf.Model.extend({
tableName: 'books',
editions: function() {
return this.hasMany(Edition);
},
chapters: function{
return this.hasMany(Chapter);
},
genre: function() {
return this.belongsTo(Genre);
}
})
new Book({'ISBN-13': '9780440180296'}).fetch({
withRelated: [
'genre', 'editions',
{ chapters: function(query) { query.orderBy('chapter_number'); }}
]
}).then(function(book) {
console.log(book.related('genre').toJSON());
console.log(book.related('editions').toJSON());
console.log(book.toJSON());
});
那么区别是什么呢?
解决方法:
没有不同.
Model.fetch,Model.query,Model.where和Model.fetchAll是以下的简写:
Model[method] = function(...args) {
return Model.forge()[method](...args);
}
而Model.forge是新手的简写.
Model.forge = function(...args) {
return new this.constructor(...args);
}
标签:knex-js,bookshelf-js,javascript,promise 来源: https://codeday.me/bug/20190829/1762133.html