Sequelizejs 中的 .save 和 .create 有什么区别?

What is the difference between .save and .create in Sequelizejs?

我是 Sequelize 的新手,正在努力理解这个非常奇怪的 ORM 新世界是如何工作的。曾经我似乎无法理解的是 Sequelizejs 中“.create”和“.save”之间的区别。我已经用两者编写了测试函数,除了语法略有不同外,它们似乎做的事情完全相同。

这是使用“.save”方法

 models.User.build({
    username: req.body.username,
    password: req.body.password,
    first_name: req.body.firstName,
    last_name: req.body.lastName
  })
  .save()
  .then(function(task){
    // some function...
  })
  .catch(function(error){
    // some function...
  });

这是使用“.create”方法

  models.User.create({
    username: req.body.username,
    password: req.body.password,
    first_name: req.body.firstName,
    last_name: req.body.lastName
  }).then(function(data) {
    // some function...
  });

我在这里没有看到什么?

当这样使用时,它们的意思是一样的。

但最重要的是,在您的第一个示例中,.build() 实例化了 ActiveRecord,它获得了关联方法以及所有 getter 和 setter 方法等方法。 .create() 方法仅在创建完成后才将 ActiveRecord 返回给您。

假设您的用户与 picture 相关联。有时您使用构建方法来执行此操作:

var user = models.User.create({
    userId: req.body.userId
});

// start doing things with the user instance

user.hasPictures().then(function(hasPictures) {
    // does user have pictures?
    console.log(hasPictures)

});

相对于这样做:

models.Picture.find({
    where: { user_fkey: req.body.userId }
}).then(function(picture) {
    if (picture) console.log('User has picture(s)');
});

更重要的是,您可能对 setter 方法更感兴趣..

假设您可能有一个 setter 方法来执行此操作:

setName: function(firstName, lastName) {
    var name;
    if (this.nationality === 'Chinese' || this.nationality === 'Korean' ) {
        name = lastName + ' ' + firstName;
    } else {
        name = firstName + ' ' + lastName;
    }
    return this.name = name
}

然后现在使用 user ActiveRecord,您可以:

user.nationality = 'Korean';
user.setDataValue('setName', 'Park', 'Ji Sung');

// call other setter methods here to complete the model.

// then finally call .save()
user.save();

如文档中所述http://docs.sequelizejs.com/en/latest/docs/instances/

方法.build()创建了一个non-persistent实例,这意味着数据没有保存在数据库中yet,但仅在执行期间存储在内存中。当您的程序停止时(服务器崩溃、执行结束或类似情况),使用 .build() 创建的实例将丢失。

这是 .save() 发挥作用的地方。它将通过.build()方法构建的实例的数据存储在数据库中。

这种方法允许您在将实例存储到数据库之前以您需要的方式对其进行操作。

.create() 方法只是 .build().save() 同一命令中的一个实例。对于不需要操作实例的简单情况,这很方便,允许您使用单个命令将数据存储在数据库中。举例说明:

这个:

User.build({ name: "John" }).save().then(function(newUser){
    console.log(newUser.name); // John
    // John is now in your db!
}).catch(function(error){
    // error
});

与此相同:

User.create({ name: "John"}).then(function(newUser){
    console.log(newUser.name); // John
    // John is now in your db!
}).catch(function(error){
    // error
});

但是你可以这样做:

var user = User.build({ name: "John"}); // nothing in your db yet

user.name = "Doe"; // still, nothing on your db

user.save().then(function(newUser){
    console.log(newUser.name); // Doe
    // Doe is now in your db!
}).catch(function(error){
    // error
});

基本上,.build().save() 使您能够在实例化后修改实例,但在将其数据存储到数据库之前。