mysql - 如何在Loopback中创建数据 View 模型?

标签 mysql node.js loopbackjs

基本上就是标题所问的内容。我想知道是否可以在 Loopback 中创建一个不了解数据源的自定义 View 模型?

我当前的流程是在 MySQL 中创建一个 View ,然后在 Loopback 中构建一个覆盖该 View 的模型,但我最近意识到,如果我们决定迁移到不同的后端,或者以某种方式更改数据源,我们必须弄清楚如何重新创建 View 。

谷歌对此的搜索显示了 bupkis,所以我想我应该把它扔在这里,看看是否有人了解这个主题。

提前致谢!

最佳答案

在 Loopback 中使用 View 效果很好。只需将 View 视为表,Loopback 就会以同样的方式对待它。事实上,如果您愿意,您实际上可以对 View 执行一些写入操作。假设您已经在 SQL 中创建了 View ,下面是从 Loopback 中的现有表或 View 创建端点的代码片段:

/**
 * Creates a REST endpoint using the persistedModel.
 * @function createPersistedModelApi
 */
function createPersistedModelApi(app, dataSourceName: string, tablename: string, callback) {

    let eventInfo: Type.Event
    let ds = app.datasources[dataSourceName];

    ds.discoverSchema(tablename, null, function(err, schema) {

        if (!err) {

            // Set the key field.                
            schema.properties.rowid.id = true;

            // Get a list of the fields
            var fields = Object.keys(schema.properties);

            // Set some properties on all fields.
            fields.forEach(function(field) {
                schema.properties[field].required = false;
                schema.properties[field].nullable = true;
            });

            // Create the model.
            ds.createModel(tablename,
                schema.properties,
                {
                    plural: tablename,
                    core: true,
                    base: "PersistedModel",
                    idInjection: false
                }
            )

            // Get an instance of the model.
            let model = ds.getModel(tablename);

            // Make the model public with a REST API.
            app.model(model, { dataSource: dataSourceName, public: true });

        // Error
        } else {
             ....
        }

        // Return
        ........

    });
}

关于mysql - 如何在Loopback中创建数据 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37393839/

相关文章:

mysql - 如何将行转换为重复的基于列的数据?

javascript - 代码在 collection.find 处停止

Node.js,表达可变权重

node.js - Node 的 Clojurescript 自编译

node.js - 环回关系数据库 hasManyThrough 数据透视表

c# - 如何安全地创建一个查询,该查询将列出给定表名的列名以及可能指向 SQL Server 或 MySQL 的连接字符串?

mysql - 如何将两个 Selects 与 Joins 相交?数据库

javascript - 如何在node/loopback中同步调用model.find方法?

javascript - 环回: Store object from remote method for later reuse within the Server

mysql - 无法找到也无法安装 mysql_config