【问题标题】:Dynamic Model Creation Loopback动态模型创建环回
【发布时间】:2017-12-06 22:02:00
【问题描述】:

我正在尝试使用 embedsOne 关系对以下内容进行建模:

var modelName = 'Customer';
var results = {};
results[modelName] = {
  "name": modelName,
  options: {
    idInjection: false
  },
  properties: {
    "custid": {
      "required": true,
      "type": "string",
      "id":1,
      "length": 30
    },
    "name": {
      "required": true,
      "type": "number",
      "id":1,
      "length": 30
    },
    "address":{
      "required": true,
      "type": "object",
      "properties": {
        "city": {
          "required": true,
          "type": "string",
          "length": 30
        }
      }
    }
  }
};

我使用以下代码在 Customer(父模型)和 Address(作为子模型)之间创建 embedsOne 关系

modelProps = results[modelName].properties;

  Object.keys(modelProps).forEach(function (field) {
    if(modelProps[field].type === "object") {
      childProps = modelProps[field];
      childProps.name = field;
      delete modelProps[field];

    }});

  console.log("modeproper: ",modelProps);
  console.log(childProps);

  var model1 = {
    "name": "Customer",
    "plural": childProps.name,
    "base": "PersistedModel",
    "idInjection": false,
    "properties": childProps.properties,
    "public": false
  };

  var childModel = loopback.createModel(model1);


  childModel.public = false;

  var config = {
    dataSource: 'dssodayana',
    "public": false
  };
  app.model(childModel, config);



  var model = {
    "name": "Customer",
    "plural": "Customer",
    "base": "PersistedModel",
    "idInjection": false,
    "properties": modelProps
  };
  var parentModel = loopback.createModel(model);
  app.model(parentModel, config);

  console.log();

  **parentModel.embedsOne(childModel, {
    as: "test", // default to the relation name - address
    property: "address" // default to addressItem
  });**
  app.model(parentModel);

现在,我想查看 parentModel。是否可以将此模型写入磁盘文件或将其转换为 json?

【问题讨论】:

  • 但这不显示关系并且子对象以'_'为前缀。有没有办法查看关系?

标签: strongloop loopback


【解决方案1】:

如果您想根据您的数据库架构动态创建模型,您可以在您的应用启动中使用此方法:

ds.discoverModelDefinitions(modelDefinitionsConf, function(err, data){
  for (var el in data) {
    (function(modelName){
      if (acceptedTables.indexOf(modelName) >= 0) {
          ds.discoverSchema(modelName, function (err, schema) {
            var test = ds.createModel(schema.name, schema.properties, schema.options);
            app.model(test, {public : true, dataSource: ds });
          });
      }
    })(data[el].name)
  }
});

这将遍历您提供的数据库源中的表,并动态创建模型并在 api 中公开它们。

【讨论】:

    【解决方案2】:

    您可以使用parentModel.definition.toJSON() 函数来打印定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2021-02-27
      • 2023-03-21
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多