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

我是新来的Sequelize,努力去理解这个非常陌生的ORM新世界是如何工作的。 曾经我似乎无法理解的东西是Sequelizejs中“.create”和“.save”之间的区别。 我用两种语言编写了testing函数,除了语法略有不同外,他们似乎也完全一样。

这是使用“.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... }); 

我在这里没有看到什么?

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

方法.build()创build一个非持久化实例,这意味着数据还没有被保存在数据库中,但是在执行过程中只存储在内存中。 当程序停止时(服务器崩溃,执行结束或类似事件),使用.build()创build的实例将会丢失。

这是.save()完成工作的地方。 它将.build()方法构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()让你能够在实例被修改后修改实例,但是在将实例的数据存储到数据库之前。

当这样使用时,它们意味着同样的事情。

但最重要的是,在你的第一个例子中, .build()实例化了ActiveRecord,它获得了关联方法和你所有的getter和setter方法。 .create()方法只有在创build完成后才能返回ActiveRecord。

假设你的用户与一张picture相关联。 有时候你使用build方法来做到这一点:

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