VIRTUAL(虛擬)
繼承自
src/data-types.js~ABSTRACT → VIRTUAL
一個不會儲存在資料庫中的虛擬值。舉例來說,如果您想在模型中提供一個預設值,該值會回傳給使用者但不會儲存在資料庫中,這會很有用。
您也可以用它來驗證一個值,然後再進行置換並儲存。VIRTUAL 也會將回傳型別和相依欄位作為參數。如果 attributes
中存在虛擬屬性,它也會自動提取額外的欄位。回傳型別主要適用於依賴類型(如 GraphQL)的設定。
範例
在雜湊密碼之前檢查密碼長度
sequelize.define('user', {
password_hash: DataTypes.STRING,
password: {
type: DataTypes.VIRTUAL,
set: function (val) {
// Remember to set the data value, otherwise it won't be validated
this.setDataValue('password', val);
this.setDataValue('password_hash', this.salt + val);
},
validate: {
isLongEnough: function (val) {
if (val.length < 7) {
throw new Error("Please choose a longer password")
}
}
}
}
})
# In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
具有相依欄位的虛擬屬性
{
active: {
type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
get: function() {
return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
}
}
}
建構子摘要
公開建構子 | ||
public |
constructor(ReturnType: ABSTRACT, fields: Array) |