Mysql Sequelizejs中的.save和.create有什么区别?
我对续集还不熟悉,我正在努力理解这个非常奇怪的新世界是如何运作的。有一件事我似乎不明白,就是Sequelizejs中“.create”和“.save”的区别。我已经用这两种语言编写了测试函数,除了语法稍有不同之外,它们似乎做的事情完全相同 这是使用“.save”方法 这是使用“.create”方法Mysql Sequelizejs中的.save和.create有什么区别?,mysql,node.js,orm,sequelize.js,Mysql,Node.js,Orm,Sequelize.js,我对续集还不熟悉,我正在努力理解这个非常奇怪的新世界是如何运作的。有一件事我似乎不明白,就是Sequelizejs中“.create”和“.save”的区别。我已经用这两种语言编写了测试函数,除了语法稍有不同之外,它们似乎做的事情完全相同 这是使用“.save”方法 这是使用“.create”方法 我在这里看不到什么?当这样使用时,它们的意思是相同的 但最重要的是,在第一个示例中,.build()实例化了ActiveRecord,它获得了关联方法以及所有getter和setter方法等方法。.c
我在这里看不到什么?当这样使用时,它们的意思是相同的 但最重要的是,在第一个示例中,
.build()
实例化了ActiveRecord,它获得了关联方法以及所有getter和setter方法等方法。.create()
方法仅在创建完成后才返回ActiveRecord
假设您的用户与图片关联。有时,您可以使用生成方法来执行此操作:
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();
如文件中所述
方法.build()创建了一个非持久性的实例,这意味着在执行过程中,数据尚未保存在数据库中,而是仅存储在内存中。当程序停止时(服务器崩溃、执行结束或类似情况),使用.build()创建的实例将丢失
这就是.save()执行其工作的地方。它将通过.build()方法生成的实例的数据存储在数据库中
这种方法允许您在将实例存储到数据库之前,以所需的方式操作实例
.create()。对于不需要操作实例的简单情况,这是一种方便,允许您使用单个命令将数据存储在数据库中。举例说明:
这:
与此相同:
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()使您能够在实例被实例化之后,但在将其数据存储到数据库之前修改实例。使用create,您不需要调用。save():)显然build()。save()
将在isNewRecord
设置为false时进行更新,但是无论isNewRecord
的值是多少,create()
都不会执行更新。(使用Sequelize v3)当您使用构建
时,对象将具有在模型中定义的默认值。
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
});