使用StrongLoop自动创建mysql表

时间:2023-02-11 09:28:58

I am trying to use Strongloop with MySql but cannot figure out how to migrate or automatically create tables into a MySql database.

我正在尝试使用MySql的Strongloop,但是我不知道如何将表迁移或自动创建到MySql数据库中。

Is there at least a way to export the models into MySql schemas or do I have to manually create the tables?

是否至少有一种方法可以将模型导出到MySql模式中,还是必须手动创建表?

I've been trying with the mysql demo app, and going over the docs for a while but no luck - http://docs.strongloop.com/display/DOC/MySQL+connector

我一直在尝试使用mysql演示应用程序,并浏览了一段时间的文档,但没有运气——http://docs.strongloop.com/display/mysql +connector

Thanks!

谢谢!

8 个解决方案

#1


7  

LoopBack calls it auto-migration. Check these links and search for that term:

回送称之为自动迁移。检查这些链接并搜索该术语:

Recipes for LoopBack Models, part 5 of 5: Model Synchronization with Relational Databases

环回模型的配方,第5部分:与关系数据库的模型同步

Data sources and connectors

数据源和连接器

#2


33  

I created /server/boot/autoupdate.js. It runs when the app boots. It loads "model-config" and "datasources" JSON and migrates or updates all models to the datasources defined for them.

我创建了/服务器/ boot / autoupdate.js。它在应用启动时运行。它加载“模型配置”和“数据源”JSON,并将所有模型迁移或更新到为它们定义的数据源。

# /server/boot/autoupdate.js
module.exports = function(app) {
    var path = require('path');
    var models = require(path.resolve(__dirname, '../model-config.json'));
    var datasources = require(path.resolve(__dirname, '../datasources.json'));

    function autoUpdateAll(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    app.dataSources[models[key].dataSource].autoupdate(key, function (err) {
                        if (err) throw err;
                        console.log('Model ' + key + ' updated');
                    });
                }
            }
        });
    }

    function autoMigrateAll(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    app.dataSources[models[key].dataSource].automigrate(key, function (err) {
                        if (err) throw err;
                        console.log('Model ' + key + ' migrated');
                    });
                }
            }
        });
    }
    //TODO: change to autoUpdateAll when ready for CI deployment to production
    autoMigrateAll();
    //autoUpdateAll();

};

#3


12  

You can simply migrate models by adding following lines to your server.js file before app.start method:

您可以通过向服务器添加以下代码行来迁移模型。开始方法:

app.datasources['mySqlConnection'].automigrate(['orders','customers', 'User', 'ACL'], function(err) {
     console.log(err);
});
  1. Add models to the array as per your need.
  2. 根据需要向数组添加模型。
  3. Run the application by slc run.
  4. 通过slc运行应用程序。

Note: mySqlConnection is the connection name, replace it by your own connection name.

注意:mySqlConnection是连接名,用您自己的连接名替换它。

#4


8  

To update and/or create all mysql tables for your models:

更新和/或为您的模型创建所有mysql表:

var dataSource = app.dataSources.mysql;       
dataSource.autoupdate(null, function (err) {
    if(err) return cb(err);
    return cb();
});      

#5


1  

In my case, I manually created MySQL tables and then created the models. For existing MySQL tables, I create the models where property names are the same as MySQL field's names.

在我的例子中,我手动创建MySQL表,然后创建模型。对于现有的MySQL表,我创建了属性名称与MySQL字段名称相同的模型。

So here are my steps in using StrongLoop LoopBack with MySQL Database:

下面是我使用StrongLoop循环到MySQL数据库的步骤:

  1. Create MySQL Database and Tables (or use existing database).
  2. 创建MySQL数据库和表(或使用现有数据库)。
  3. Install MySQL connector using npm install loopback-connector-mysql --save
  4. 使用npm安装MySQL connector- save
  5. Add your MySQL Database details on datasources.json file.
  6. 在数据源上添加MySQL数据库细节。json文件。
  7. Create a model for each table using slc lb model tablename -i OR edit models.json file and add the properties manually. (document: http://docs.strongloop.com/display/DOC/Creating+a+LoopBack+application#CreatingaLoopBackapplication-Creatingmodels)
  8. 使用slc lb模型tablename -i或编辑模型为每个表创建一个模型。json文件并手动添加属性。(文档:http://docs.strongloop.com/display/DOC/Creating + +回送+应用程序# CreatingaLoopBackapplication-Creatingmodels)
  9. Properties' names should be the same as MySQL field's names (more information on mapping MySQL to JSON data types: http://docs.strongloop.com/display/DOC/MySQL+connector#MySQLconnector-MySQLtoJSONtypes)
  10. 属性的名称应该与MySQL字段的名称相同(更多关于将MySQL映射到JSON数据类型的信息:http://docs.strongloop.com/display/mysql +connector#MySQLconnector-MySQLtoJSONtypes)

#6


0  

In the same kind of issue, if you need to automatically create a database, you can use the createDatabase option in your dataSource JSON file.

在同样的问题中,如果需要自动创建数据库,可以在数据源JSON文件中使用createDatabase选项。

  "mysql": {
    "host": "localhost",
    "port": 0,
    "database": "db",
    "username": "root",
    "password": "",
    "name": "mysql",
    "connector": "mysql",
    "debug": false,
    "createDatabase": true
  }

So you don't need to write yourself the queries to create the base. Hope it helps.

因此,您不需要自己编写查询来创建基。希望它可以帮助。

#7


0  

i discovered an easy way to accomplish this task. The reference link is: Clique Here

我发现了一种简单的方法来完成这项任务。参考链接是:小团体在这里

You can use prototype or not, in my case, i do nott used.

你可以用原型或不,在我的情况下,我没有使用。

For the documentation, you should use:

对于文档,您应该使用:



    ds.autoupdate (models, function (error) {
        if (!error) {
            console.log( "Updated models.");
        }else{
            console.log( "An error has occurred:" + error);
        }
        ds.disconnect();
    });

Where:

地点:



    var path = require ( 'path');
    var app = require (path.resolve (__ dirname, '../server/server'));
    var ds = app.datasources.x;

and x is datasource attribute name, example of /server/datasources.json:

x是数据源属性名,例如/server/datasource .json:



    {
      "x": {
        "Host": "localhost"
        "Port": 3306,
        "Database", "loopapp"
        "Password": "",
        "Name": "x"
        "User", "root"
        "Connector": "mysql"
      }
    }

Note (1): Models can be the string model name or the array of string (models names).

注意(1):模型可以是字符串模型名称或字符串数组(模型名称)。

Note (2): If you prefer not to put models, all models of the file whose base attribute equals "PersistedModel", will be updated.

注意(2):如果您不喜欢放置模型,则将更新基属性为“PersistedModel”的文件的所有模型。

With that, i used like this:

我这样用:


    autoupdate function () {
        ds.autoupdate (function (error) {
          if (!error) {
                console.log( "Updated all models");
          }else {
                console.log( "An error has occurred:" + error);
          }
          ds.disconnect();
        });
    }
    

and i called the: autoupdate();

我调用:autoupdate();

You can put this code in a file.js and call the command line: node file.js.

你可以把这些代码放在一个文件里。并调用命令行:node file.js。

If you want this file to be called every time you start the program, put it on /server/boot/file.js path.

如果希望在每次启动程序时调用此文件,请将其放在/server/boot/file中。js的道路。

Obviously, if you want to use automigrate, only replace the autoupdate word in the code above, by automigrate.

显然,如果你想使用自动排序,只需要用自动排序来替换上面代码中的自动排序。

#8


0  

jduhls answer is beautiful, but I needed to tweak it slightly to add some static data into tables. Here's my tweaked version, along with an example of loading data into a simple SystemSettings table (id, settingName, settingValue):

jduhls的答案很漂亮,但是我需要稍微调整一下,以便向表中添加一些静态数据。下面是我的修改版本,以及将数据加载到一个简单的SystemSettings表中的示例(id、settingName、settingValue):

var async = require('async');

var SYSTEM_SETTINGS = [
  {
    "settingName": "mustPayInAdvance",
    "settingValue": "false",
  }
];

module.exports = function(app) {
    var path = require('path');
    var models = require(path.resolve(__dirname, '../model-config.json'));
    var datasources = require(path.resolve(__dirname, '../datasources.json'));
    var modelUpdates = [];

    function buildModelListForOperation(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    modelUpdates.push({operation: app.dataSources[models[key].dataSource], key: key});
                }
            }
        });
    }

    function createStaticData() {
        app.models.SystemSettings.create(SYSTEM_SETTINGS, function(err, created) {
            if (err) 
                throw err;
            else
                console.log('Sample data was imported.');
        });
    }

    function processModelsAndData(operationType) {
        buildModelListForOperation();

        // Create all models
        async.each(modelUpdates, function(item, callback) {
            item.operation[operationType](item.key, function (err) {
                if (err) throw err;
                console.log('Model ' + item.key + ' migrated');
                callback();
            });
        }, function (err) {
            if (err) throw err;
            createStaticData();
        });    
    }

    //TODO: change to 'autoupdate' when ready for CI deployment to production
    processModelsAndData('automigrate');
};

#1


7  

LoopBack calls it auto-migration. Check these links and search for that term:

回送称之为自动迁移。检查这些链接并搜索该术语:

Recipes for LoopBack Models, part 5 of 5: Model Synchronization with Relational Databases

环回模型的配方,第5部分:与关系数据库的模型同步

Data sources and connectors

数据源和连接器

#2


33  

I created /server/boot/autoupdate.js. It runs when the app boots. It loads "model-config" and "datasources" JSON and migrates or updates all models to the datasources defined for them.

我创建了/服务器/ boot / autoupdate.js。它在应用启动时运行。它加载“模型配置”和“数据源”JSON,并将所有模型迁移或更新到为它们定义的数据源。

# /server/boot/autoupdate.js
module.exports = function(app) {
    var path = require('path');
    var models = require(path.resolve(__dirname, '../model-config.json'));
    var datasources = require(path.resolve(__dirname, '../datasources.json'));

    function autoUpdateAll(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    app.dataSources[models[key].dataSource].autoupdate(key, function (err) {
                        if (err) throw err;
                        console.log('Model ' + key + ' updated');
                    });
                }
            }
        });
    }

    function autoMigrateAll(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    app.dataSources[models[key].dataSource].automigrate(key, function (err) {
                        if (err) throw err;
                        console.log('Model ' + key + ' migrated');
                    });
                }
            }
        });
    }
    //TODO: change to autoUpdateAll when ready for CI deployment to production
    autoMigrateAll();
    //autoUpdateAll();

};

#3


12  

You can simply migrate models by adding following lines to your server.js file before app.start method:

您可以通过向服务器添加以下代码行来迁移模型。开始方法:

app.datasources['mySqlConnection'].automigrate(['orders','customers', 'User', 'ACL'], function(err) {
     console.log(err);
});
  1. Add models to the array as per your need.
  2. 根据需要向数组添加模型。
  3. Run the application by slc run.
  4. 通过slc运行应用程序。

Note: mySqlConnection is the connection name, replace it by your own connection name.

注意:mySqlConnection是连接名,用您自己的连接名替换它。

#4


8  

To update and/or create all mysql tables for your models:

更新和/或为您的模型创建所有mysql表:

var dataSource = app.dataSources.mysql;       
dataSource.autoupdate(null, function (err) {
    if(err) return cb(err);
    return cb();
});      

#5


1  

In my case, I manually created MySQL tables and then created the models. For existing MySQL tables, I create the models where property names are the same as MySQL field's names.

在我的例子中,我手动创建MySQL表,然后创建模型。对于现有的MySQL表,我创建了属性名称与MySQL字段名称相同的模型。

So here are my steps in using StrongLoop LoopBack with MySQL Database:

下面是我使用StrongLoop循环到MySQL数据库的步骤:

  1. Create MySQL Database and Tables (or use existing database).
  2. 创建MySQL数据库和表(或使用现有数据库)。
  3. Install MySQL connector using npm install loopback-connector-mysql --save
  4. 使用npm安装MySQL connector- save
  5. Add your MySQL Database details on datasources.json file.
  6. 在数据源上添加MySQL数据库细节。json文件。
  7. Create a model for each table using slc lb model tablename -i OR edit models.json file and add the properties manually. (document: http://docs.strongloop.com/display/DOC/Creating+a+LoopBack+application#CreatingaLoopBackapplication-Creatingmodels)
  8. 使用slc lb模型tablename -i或编辑模型为每个表创建一个模型。json文件并手动添加属性。(文档:http://docs.strongloop.com/display/DOC/Creating + +回送+应用程序# CreatingaLoopBackapplication-Creatingmodels)
  9. Properties' names should be the same as MySQL field's names (more information on mapping MySQL to JSON data types: http://docs.strongloop.com/display/DOC/MySQL+connector#MySQLconnector-MySQLtoJSONtypes)
  10. 属性的名称应该与MySQL字段的名称相同(更多关于将MySQL映射到JSON数据类型的信息:http://docs.strongloop.com/display/mysql +connector#MySQLconnector-MySQLtoJSONtypes)

#6


0  

In the same kind of issue, if you need to automatically create a database, you can use the createDatabase option in your dataSource JSON file.

在同样的问题中,如果需要自动创建数据库,可以在数据源JSON文件中使用createDatabase选项。

  "mysql": {
    "host": "localhost",
    "port": 0,
    "database": "db",
    "username": "root",
    "password": "",
    "name": "mysql",
    "connector": "mysql",
    "debug": false,
    "createDatabase": true
  }

So you don't need to write yourself the queries to create the base. Hope it helps.

因此,您不需要自己编写查询来创建基。希望它可以帮助。

#7


0  

i discovered an easy way to accomplish this task. The reference link is: Clique Here

我发现了一种简单的方法来完成这项任务。参考链接是:小团体在这里

You can use prototype or not, in my case, i do nott used.

你可以用原型或不,在我的情况下,我没有使用。

For the documentation, you should use:

对于文档,您应该使用:



    ds.autoupdate (models, function (error) {
        if (!error) {
            console.log( "Updated models.");
        }else{
            console.log( "An error has occurred:" + error);
        }
        ds.disconnect();
    });

Where:

地点:



    var path = require ( 'path');
    var app = require (path.resolve (__ dirname, '../server/server'));
    var ds = app.datasources.x;

and x is datasource attribute name, example of /server/datasources.json:

x是数据源属性名,例如/server/datasource .json:



    {
      "x": {
        "Host": "localhost"
        "Port": 3306,
        "Database", "loopapp"
        "Password": "",
        "Name": "x"
        "User", "root"
        "Connector": "mysql"
      }
    }

Note (1): Models can be the string model name or the array of string (models names).

注意(1):模型可以是字符串模型名称或字符串数组(模型名称)。

Note (2): If you prefer not to put models, all models of the file whose base attribute equals "PersistedModel", will be updated.

注意(2):如果您不喜欢放置模型,则将更新基属性为“PersistedModel”的文件的所有模型。

With that, i used like this:

我这样用:


    autoupdate function () {
        ds.autoupdate (function (error) {
          if (!error) {
                console.log( "Updated all models");
          }else {
                console.log( "An error has occurred:" + error);
          }
          ds.disconnect();
        });
    }
    

and i called the: autoupdate();

我调用:autoupdate();

You can put this code in a file.js and call the command line: node file.js.

你可以把这些代码放在一个文件里。并调用命令行:node file.js。

If you want this file to be called every time you start the program, put it on /server/boot/file.js path.

如果希望在每次启动程序时调用此文件,请将其放在/server/boot/file中。js的道路。

Obviously, if you want to use automigrate, only replace the autoupdate word in the code above, by automigrate.

显然,如果你想使用自动排序,只需要用自动排序来替换上面代码中的自动排序。

#8


0  

jduhls answer is beautiful, but I needed to tweak it slightly to add some static data into tables. Here's my tweaked version, along with an example of loading data into a simple SystemSettings table (id, settingName, settingValue):

jduhls的答案很漂亮,但是我需要稍微调整一下,以便向表中添加一些静态数据。下面是我的修改版本,以及将数据加载到一个简单的SystemSettings表中的示例(id、settingName、settingValue):

var async = require('async');

var SYSTEM_SETTINGS = [
  {
    "settingName": "mustPayInAdvance",
    "settingValue": "false",
  }
];

module.exports = function(app) {
    var path = require('path');
    var models = require(path.resolve(__dirname, '../model-config.json'));
    var datasources = require(path.resolve(__dirname, '../datasources.json'));
    var modelUpdates = [];

    function buildModelListForOperation(){
        Object.keys(models).forEach(function(key) {
            if (typeof models[key].dataSource != 'undefined') {
                if (typeof datasources[models[key].dataSource] != 'undefined') {
                    modelUpdates.push({operation: app.dataSources[models[key].dataSource], key: key});
                }
            }
        });
    }

    function createStaticData() {
        app.models.SystemSettings.create(SYSTEM_SETTINGS, function(err, created) {
            if (err) 
                throw err;
            else
                console.log('Sample data was imported.');
        });
    }

    function processModelsAndData(operationType) {
        buildModelListForOperation();

        // Create all models
        async.each(modelUpdates, function(item, callback) {
            item.operation[operationType](item.key, function (err) {
                if (err) throw err;
                console.log('Model ' + item.key + ' migrated');
                callback();
            });
        }, function (err) {
            if (err) throw err;
            createStaticData();
        });    
    }

    //TODO: change to 'autoupdate' when ready for CI deployment to production
    processModelsAndData('automigrate');
};