Skip to content
On this page

属性修改器

访问器、修改器允许您在模型实例上检索或设置 Sutando 属性值时对其进行转换。

访问器 & 修改器

定义一个访问器

若要定义一个访问器,则需在模型上创建一个 get{Attribute}Attribute 方法,要访问的 {Attribute} 字段需使用「驼峰式」命名。

在这个示例中,我们将为 first_name 属性定义一个访问器。当 Sutando 尝试获取 first_name 属性时,将自动调用此访问器:

js
const { Model } = require('sutando');

class User extends Model {
  getFirstNameAttribute(value) {
    return value.toUpperCase();
  }
}

如你所见,字段的原始值被传递到访问器中,允许你对它进行处理并返回结果。如果想获取被修改后的值,你可以在模型实例上访问 first_name 属性:

js
const user = await User.query().find(1);
 
const firstName = user.first_name;

当然,你也可以通过已有的属性值,使用访问器返回新的计算值:

js
getFullNameAttribute() {
  return `${this.first_name} ${this.last_name}`;
}

定义一个修改器

若要定义一个修改器,则需在模型上面定义 set{Attribute}Attribute 方法。要访问的 {Attribute} 字段使用「驼峰式」命名。让我们再来定义一个 first_name 属性的修改器。当我们尝试在模式上在设置 first_name 属性值时,该修改器将被自动调用:

js
const { Model } = require('sutando');

class User extends Model {
  setFirstNameAttribute(value) {
    this.atttributes.first_name = value.toLocalLowerCase();
  }
}

修改器会获取属性已经被设置的值,并允许你修改并且将其值设置到 Sutando 模型内部的 attributes 属性上。 使用修改器,我们只需要设置 Sutando 模型的 first_name 属性即可:

js
const user = User.query().find(1);

user.first_name = 'Sally';

在这个例子中,setFirstNameAttribute 方法在调用的时候接受 Sally 这个值作为参数。 接着修改器会调用 toLocalLowerCase 方法并将处理的结果设置到内部的 attributes 数组。

Released under the MIT License. (dev)