简体   繁体   English

Sequelize 中的 .sync() 到底有什么用?

[英]What is really .sync() in Sequelize for?

I am a newby with Sequelize and Node.js in general, I am wondering if .sync() is ever needed for anything else than creating and structuring a database to fit exactly with your project in the development phase.我是 Sequelize 和 Node.js 的新手,我想知道除了在开发阶段创建和构建数据库以完全适合您的项目之外,是否还需要 .sync() 。

Take the following example: If I already have my database structure (made with MySQL Workbench or whatever), is it useful somehow to ever use .sync()?以下面的例子为例:如果我已经有了我的数据库结构(用 MySQL Workbench 或其他东西制作),那么使用 .sync() 是否有用? Does it have any important application in production?它在生产中有什么重要的应用吗?

If I already have my database structure (made with MySQL Workbench or whatever), is it useful somehow to ever use .sync()?如果我已经有了我的数据库结构(用 MySQL Workbench 或其他东西制作),那么使用 .sync() 是否有用? Does it have any important application in production?它在生产中有什么重要的应用吗?

No. Sequelize sync will create tables that do not exists.不。Sequelize sync将创建不存在的表。 If you already have all the tables, it will not do anything.如果您已经拥有所有表,则它不会执行任何操作。 However if you use force: true , it will drop the table that exists and recreate them from the model definition.但是,如果您使用force: true ,它将删除存在的表并从模型定义中重新创建它们。

On a separate note, one should prefer migrations over sync .另一方面,人们应该更喜欢migrations不是sync sync does not reflect tale alterations. sync不反映故事更改。 Migrations are more powerful, you can undo, redo and much more with it.迁移功能更强大,您可以使用它撤消、重做等等。

Here is a good answer on Sequelize.js: how to use migrations and sync这是Sequelize.js上的一个很好的答案:如何使用迁移和同步

sequelize.sync() creates tables for all models that were defined (ie, using the define method on an instance of Sequelize). sequelize.sync()为所有定义的模型创建表(即,在 Sequelize 的实例上使用 define 方法)。 It syncs models to the database by creating the appropriate tables, and if applicable, relations.它通过创建适当的表和关系(如果适用)将模型同步到数据库。

Example:例子:

sequelize
  .sync()
  .then(result => {
    console.log(result);
  })
  .catch(err => console.log(err));

This is what was at the beginning of the console log (the 'products' table was created based on the 'product' model; it's automatically pluralized):这是控制台日志开头的内容(“产品”表是基于“产品”模型创建的;它会自动复数):

Executing (default): CREATE TABLE IF NOT EXISTS `products` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `price` DOUBLE PRECISION NOT NULL, `imageUrl` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM