如何在环回中创建双向hasOne关系

时间:2018-07-26 21:17:41

标签: javascript loopbackjs loopback has-one

我有模特儿,一句话。每个单词都有一个名为equivalent的属性,具有与其他性别相同的单词,例如,兄弟->姐姐,姐姐->兄弟。

我的单词模型如下:

{
  "name": "word",
  "plural": "words",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "word": {
      "type": "string",
      "required": true
    },
    "definition": {
      "type": "string"
    },
    "tags": {
      "type": [
        "string"
      ]
    },
    "synonyms": {
      "type": [
        "string"
      ]
    },
    "gender": {
      "type": "string",
      "required": true
    },
    "equivalent": {
      "type": "string"
    }
  },
  "relations": {
    "equivalent-word": {
      "type": "hasOne",
      "model": "word",
      "foreignKey": "equivalentId"
    }
  }
}

示例数据:

{
    "word":"sister",
    "definition":"Ecclesiastical Used as a form of address for such a woman, alone or followed by the woman's name.",
    "tags":["wordnik"],
    "gender":"female",
    "equivalent":"brother",
    "id":10
},
    "word":"brother", 
    "definition":"A male person who has the same father and mother with another person, or who has one of them only. In the latter case he is more definitely called a half brother, or brother of the half blood.",
    "tags":["wordnik"],
    "gender":"male",
    "equivalent":"sister",
    "id":1143
}

在启动脚本中,我遍历每个实例并设置了EquivalentId,但它不起作用。当我尝试通过"message": "Unknown \"word\" id \"undefined\"."

获得等价物时,我得到http://localhost:3000/api/words/10/equivalent-word
module.exports = function(app) {
  var data = require("../all.json");
  var Word = app.models.word;
  app.dataSources.db.automigrate('word', function(err) {
    Word.create(data, function(err, instances) {
      instances.forEach(function(entry) {
        const word = entry['word'];
        const equiv = entry['equivalent'];
        if (equiv) {
          let equivalent = { "where": { "word": equiv } };
          Word.findOne(equivalent, function(err, instance) {
            console.log(instance, entry);
            entry.equivalentId = instance.id;
            instance.equivalentId = entry.id;
          }); 
        }
      });
    });
  });
};

0 个答案:

没有答案