构建非持久性实例

构建非持久性实例

为了创建定义类的实例,请执行以下操作. 如果你以前编写过 Ruby,你可能认识该语法. 使用 build - 该方法将返回一个未保存的对象,你要明确地保存它.

const project = Project.build({
  title: 'my awesome project',
  description: 'woot woot. this will make me a rich man'
})

const task = Task.build({
  title: 'specify the project idea',
  description: 'bla',
  deadline: new Date()
})

内置实例在定义时会自动获取默认值:

// 首先定义模型
class Task extends Model {}
Task.init({
  title: Sequelize.STRING,
  rating: { type: Sequelize.TINYINT, defaultValue: 3 }
}, { sequelize, modelName: 'task' });

// 现在实例化一个对象
const task = Task.build({title: 'very important task'})

task.title  // ==> 'very important task'
task.rating // ==> 3

要将其存储在数据库中,请使用 save 方法并捕获事件(如果需要):

project.save().then(() => {
  // 回调
})

task.save().catch(error => {
  // 呃
})

// 还可以使用链式构建来保存和访问对象:
Task
  .build({ title: 'foo', description: 'bar', deadline: new Date() })
  .save()
  .then(anotherTask => {
    // 你现在可以使用变量 anotherTask 访问当前保存的任务
  })
  .catch(error => {
    // Ooops,做一些错误处理
  })