如何在Loopback中创建数据视图模型? [英] How to create data view models in Loopback?

查看:150
本文介绍了如何在Loopback中创建数据视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上是标题要求的内容.我想知道是否有可能在Loopback中创建一个对数据源不了解的自定义视图模型?

Basically what the title asks. I'm wondering if it's possible to create a a custom view model in Loopback that is datasource ignorant?

我当前的过程是在MySQL中创建一个视图,然后在Loopback中构建一个覆盖该视图的模型,但是我最近意识到,如果我们决定迁移到其他后端,或者以某种方式更改数据源,我们必须找出如何重新创建视图.

My current process has been to create a view in MySQL, and then build a model in Loopback that overlays the view, but I recently realized that if we decide to migrate to a different back end, or change the datasource somehow, we'd have to figure out how to recreate the view.

对此的Google搜索显示了bupkis,所以我想把它扔出去看看是否有人对此主题有所了解.

Google searches on this have revealed bupkis, so I figured I'd throw it out here to see if anyone has knowledge on the topic.

提前谢谢!

推荐答案

在Loopback中使用视图效果很好.只需将视图视为表即可,Loopback将以相同的方式对待它.实际上,如果需要,您实际上可以对视图执行一些写操作.假设您已经在SQL中创建了视图,下面是一个片段,可从现有表或Loopback中的视图创建端点:

Using views in Loopback works well. Just treat the view as if it were a table and Loopback will treat it the same way. In fact you can actually perform some write operations against the view if you want to. Assuming you have already created the view in SQL here's a snippet to create end-points from an existing table or view in Loopback:

/**
 * 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
        ........

    });
}

这篇关于如何在Loopback中创建数据视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆