我可以向模型添加非持久字段吗?
Can I add non-persistent fields to a model?
是否有向对象模型对象添加非持久属性以使其不会覆盖预定义属性的推荐做法?
异议模型有 virtualAttributes 字段。来自文档:
The virtual values are not written to database. Only the “external” JSON format will contain them.
请务必注意,这些是函数,而不仅仅是模型属性。
来自文档的示例:
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"}
是否有向对象模型对象添加非持久属性以使其不会覆盖预定义属性的推荐做法?
异议模型有 virtualAttributes 字段。来自文档:
The virtual values are not written to database. Only the “external” JSON format will contain them.
请务必注意,这些是函数,而不仅仅是模型属性。
来自文档的示例:
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"}