获取 Bookshelf.js 模型时 "new" 的用法有何不同?
What is the difference in usage "new" while fetching Bookshelf.js models?
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
是 shorthands for:
Model[method] = function(...args) {
return Model.forge()[method](...args);
}
而 Model.forge
是 shorthand 对于 new
。
Model.forge = function(...args) {
return new this.constructor(...args);
}
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
是 shorthands for:
Model[method] = function(...args) {
return Model.forge()[method](...args);
}
而 Model.forge
是 shorthand 对于 new
。
Model.forge = function(...args) {
return new this.constructor(...args);
}