3
是否有將非持久屬性添加到Objection模型對象以避免覆蓋預定義屬性的推薦做法?我可以將非持久性字段添加到模型嗎?
是否有將非持久屬性添加到Objection模型對象以避免覆蓋預定義屬性的推薦做法?我可以將非持久性字段添加到模型嗎?
異議模型有virtualAttributes字段。從文檔:
虛擬值不寫入數據庫。只有「外部」JSON格式將包含它們。
重要的是要注意這些是功能,而不僅僅是模型屬性。從文檔
實施例:
class Person extends Model {
static get virtualAttributes() {
return ['fullName', 'isFemale'];
}
fullName() {
return `${this.firstName} ${this.lastName}`;
}
get isFemale() {
return this.gender === 'female';
}
}
const person = Person.fromJson({
firstName: 'Jennifer',
lastName: 'Aniston',
gender: 'female'
});
console.log(person.toJSON());
// --> {"firstName": "Jennifer", "lastName": "Aniston", "isFemale": true, "fullName": "Jennifer Aniston"}