基本上就是标题所问的内容。我想知道是否可以在 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/