环回 - 链接相关模型与代码

时间:2015-06-29 22:50:30

标签: node.js relationship loopbackjs

我正在加载一些示例数据,以帮助我在开发周期中进行测试。有些模型是相关的,所以我想添加它们。

问题在于我无法弄清楚如何使用代码链接两个模型。这就是我到目前为止所做的:

app.models.Region.count({}).then(function (count) {
    if (count > 0) throw "There are regions already";

    return app.models.Region.create({
      "type": "Europe"
    });
  }).then(function (region) {
    console.log("Region created", region);

    return app.models.Country.count({}).then(function (count) {
      if (count > 0) throw "There are countries already";

      return app.models.Country.create({
        "countryCode": "es",
        "regions": [region]
      });
    }).then(function (country) {
      console.log("Country created", country.regions);
      //country.regions = region
      //country.save();
    })
  }).catch(function (err) {
    console.log(err);
  });

我的国家模型有这种关系:

"regions": {
      "type": "hasMany",
      "model": "Region",
      "foreignKey": ""
    }

1 个答案:

答案 0 :(得分:1)

我认为您可能希望在创建国家/地区或切换创建顺序后创建区域。

在这里创建国家之后的地区。

app.models.Region.count({}).then(function (count) {
    if (count > 0) throw "There are regions already";

    return app.models.Region.create({
      "type": "Europe"
    });
  }).then(function (region) {
    console.log("Region created", region);

    return app.models.Country.count({}).then(function (count) {
      if (count > 0) throw "There are countries already";

      return app.models.Country.create({
        "countryCode": "es"
      });
    }).then(function (country) {
      // use this extra line
      return country.regions.create(region);
    }).then(function (country) {
      console.log("Country created", country.regions);
      //country.regions = region
      //country.save();
    })
  }).catch(function (err) {
    console.log(err);
  });

以下是您可以如何交换创作顺序,以便从相反的方向开始。

return app.models.Country.count({}).then(function (count) {
  if (count > 0) throw "There are countries already";

  return app.models.Country.create({
    "countryCode": "es"
  });

}).then(function (country) {
  console.log("Country created", country);

  return app.models.Region.count({}).then(function (count) {
    if (count > 0) throw "There are regions already";

    return country.regions.create({
      "type": "Europe"
    });
  }).then(function (region) {
    console.log("Region created", region);
    console.log("Country has regions", country.regions);

  }).catch(function (err) {
    console.log(err);
  });

})

请注意,如果这是测试数据的全部内容,那么您应该真正研究环回测试,请参阅building test data

部分