动态模型创建环回

时间:2016-06-02 15:53:14

标签: strongloop loopback

我正在尝试使用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?

2 个答案:

答案 0 :(得分:1)

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

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中公开它们。

答案 1 :(得分:0)

您可以使用PendingIntent功能打印定义。