2017-03-02 88 views

回答

2

異議模型有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"} 
相關問題