Sequelize 中文文档 v4 - Instances - 实例

Instances - 实例

此系列文章的应用示例已发布于 GitHub: sequelize-docs-Zh-CN. 能够 Fork 帮助改进或 Star 关注更新. 欢迎 Star.git

构建非持久性实例

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

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()
})

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

// 首先定义模型
const Task = sequelize.define('task', {
  title: Sequelize.STRING,
  rating: { type: Sequelize.STRING, defaultValue: 3 }
})
 
// 如今实例化一个对象
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,作一些错误处理
  })

建立持久性实例

除了构建对象以外,还须要一个明确的保存调用来存储在数据库中,能够经过一个命令执行全部这些步骤。 它被称为 create并发

Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => {
  // 你如今能够经过变量 task 来访问新建立的 task
})

也能够经过 create 方法定义哪些属性能够设置。 若是你建立基于可由用户填写的表单的数据库条目,这将很是方便。 例如,使用这种方式,你能够限制 User 模型,仅设置 username 和 address,而不是 admin 标志:ide

User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => {
  // 咱们假设 isAdmin 的默认值为 false:
  console.log(user.get({
    plain: true
  })) // => { username: 'barfooz', isAdmin: false }
})

更新 / 保存 / 持久化一个实例

如今能够更改一些值并将更改保存到数据库...有两种方法能够实现:oop

// 方法 1
task.title = 'a very different title now'
task.save().then(() => {})
 
// 方法 2
task.update({
  title: 'a very different title now'
}).then(() => {})

经过传递列名数组,调用 save 时也能够定义哪些属性应该被保存。 当您基于先前定义的对象设置属性时,这是有用的。 例如。 若是您经过Web应用程序的形式获取对象的值。 此外,这在 update 内部使用。 它就像这样:ui

task.title = 'foooo'
task.description = 'baaaaaar'
task.save({fields: ['title']}).then(() => {
 // title 如今将是 “foooo”,而 description 与之前同样
})
 
// 使用等效的 update 调用以下所示:
task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(() => {
 //  title 如今将是 “foooo”,而 description 与之前同样
})

当你调用 save 而不改变任何属性的时候,这个方法什么都不执行。this

销毁 / 删除持久性实例

建立对象并得到对象的引用后,能够从数据库中删除它。 相关的方法是 destroyidea

Task.create({ title: 'a task' }).then(task => {
  // 获取到 task 对象...
  return task.destroy();
}).then(() => {
 // task 对象已被销毁
})

若是 paranoid 选项为 true,则不会删除该对象,而将 deletedAt 列设置为当前时间戳。 要强制删除,能够将 force: true 传递给 destroy 调用:

task.destroy({ force: true })

批量操做(一次建立,更新和销毁多行)

除了更新单个实例以外,你还能够一次建立,更新和删除多个实例。 调用你须要的方法

  • Model.bulkCreate
  • Model.update
  • Model.destroy

因为你使用多个模型,回调将不会返回DAO实例。 BulkCreate将返回一个模型实例/DAO的数组,可是它们不一样于create,没有 autoIncrement 属性的结果值. updatedestroy 将返回受影响的行数。

首先看下 bulkCreate

User.bulkCreate([
  { username: 'barfooz', isAdmin: true },
  { username: 'foo', isAdmin: true },
  { username: 'bar', isAdmin: false }
]).then(() => { // 注意: 这里没有凭据, 然而如今你须要...
  return User.findAll();
}).then(users => {
  console.log(users) // ... 以获取 user 对象的数组
})

一次更新几行:

Task.bulkCreate([
  {subject: 'programming', status: 'executing'},
  {subject: 'reading', status: 'executing'},
  {subject: 'programming', status: 'finished'}
]).then(() => {
  return Task.update(
    { status: 'inactive' }, /* 设置属性的值 */,
    { where: { subject: 'programming' }} /* where 规则 */
  );
}).spread((affectedCount, affectedRows) => {
  // .update 在数组中返回两个值,所以咱们使用 .spread
  // 请注意,affectedRows 只支持以 returning: true 的方式进行定义
  
  // affectedCount 将会是 2
  return Task.findAll();
}).then(tasks => {
  console.log(tasks) // “programming” 任务都将处于 “inactive” 状态
})

而后删除它们:

Task.bulkCreate([
  {subject: 'programming', status: 'executing'},
  {subject: 'reading', status: 'executing'},
  {subject: 'programming', status: 'finished'}
]).then(() => {
  return Task.destroy({
    where: {
      subject: 'programming'
    },
    truncate: true /* 这将忽 where 并用 truncate table 替代  */
  });
}).then(affectedRows => {
  // affectedRows 将会是 2
  return Task.findAll();
}).then(tasks => {
  console.log(tasks) // 显示 tasks 内容
})

若是您直接从 user 接受值,则限制要实际插入的列可能会更好。bulkCreate() 接受一个选项对象做为第二个参数。 该对象能够有一个 fields 参数(一个数组),让它知道你想要明确构建哪些字段

User.bulkCreate([
  { username: 'foo' },
  { username: 'bar', admin: true}
], { fields: ['username'] }).then(() => {
  // admin 将不会被构建
})

bulkCreate 最初是成为 主流/快速 插入记录的方法,可是有时您但愿可以同时插入多行而不牺牲模型验证,即便您明确地告诉 Sequelize 去筛选哪些列。 你能够经过在options对象中添加一个 validate: true 属性来实现。

const Tasks = sequelize.define('task', {
  name: {
    type: Sequelize.STRING,
    validate: {
      notNull: { args: true, msg: 'name cannot be null' }
    }
  },
  code: {
    type: Sequelize.STRING,
    validate: {
      len: [3, 10]
    }
  }
})
 
Tasks.bulkCreate([
  {name: 'foo', code: '123'},
  {code: '1234'},
  {name: 'bar', code: '1'}
], { validate: true }).catch(errors => {

  /* console.log(errors) 看起来像这样:
  [
    { record:
    ...
    errors:
      { name: 'SequelizeValidationError',
        message: 'Validation error',
        errors: [Object] } },
    { record:
      ...
      errors:
        { name: 'SequelizeValidationError',
        message: 'Validation error',
        errors: [Object] } }
  ]
  */
  
})

一个实例的值

若是你记录一个实例,你会注意到有不少额外的东西。 为了隐藏这些东西并将其减小到很是有趣的信息,您可使用 get 属性。 使用选项 plain: true 调用它将只返回一个实例的值。

Person.create({
  name: 'Rambow',
  firstname: 'John'
}).then(john => {
  console.log(john.get({
    plain: true
  }))
})
 
// 结果:
 
// { name: 'Rambow',
//   firstname: 'John',
//   id: 1,
//   createdAt: Tue, 01 May 2012 19:12:16 GMT,
//   updatedAt: Tue, 01 May 2012 19:12:16 GMT
// }

提示: 您还可使用 JSON.stringify(instance) 将一个实例转换为 JSON。 基本上与 values 返回的相同。

重载实例

若是你须要让你的实例同步,你可使用 reload 方法。 它将从数据库中获取当前数据,并覆盖调用该方法的模型的属性。

Person.findOne({ where: { name: 'john' } }).then(person => {
  person.name = 'jane'
  console.log(person.name) // 'jane'
 
  person.reload().then(() => {
    console.log(person.name) // 'john'
  })
})

递增

为了增长实例的值而不发生并发问题,您可使用 increment

首先,你能够定义一个字段和要添加的值。

User.findById(1).then(user => {
  return user.increment('my-integer-field', {by: 2})
}).then(/* ... */)

而后,你能够定义多个字段和要添加到其中的值。

User.findById(1).then(user => {
  return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)

最后,你能够定义一个包含字段及其递增值的对象。

User.findById(1).then(user => {
  return user.increment({
    'my-integer-field':    2,
    'my-very-other-field': 3
  })
}).then(/* ... */)

递减

为了减小一个实例的值而不遇到并发问题,你可使用 decrement

首先,你能够定义一个字段和要添加的值。

User.findById(1).then(user => {
  return user.decrement('my-integer-field', {by: 2})
}).then(/* ... */)

而后,你能够定义多个字段和要添加到其中的值。

User.findById(1).then(user => {
  return user.decrement([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)

最后, 你能够定义一个包含字段及其递减值的对象。

User.findById(1).then(user => {
  return user.decrement({
    'my-integer-field':    2,
    'my-very-other-field': 3
  })
}).then(/* ... */)

若是这篇文章对您有帮助, 感谢 下方点赞 或 Star GitHub: sequelize-docs-Zh-CN 支持, 谢谢.

相关文章
相关标签/搜索