正确的方法来定义Loopback.io belongsTo relationship

时间:2018-06-06 08:14:37

标签: loopbackjs

我在2个Loopback模型之间有一个简单的has_many-belongsst_to关系:

{
  "name": "ApiUser",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "postgresql": {
      "table": "users"
    },
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "type": "string",
      "id": true,
      "required": true,
      "defaultFn": "uuid",
      "postgresql": {
        "dataType": "uuid"
      }
    },
    "email": {
        ...

{
  "name": "ShopifyAccount",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "api_key": {
      "type": "string",
      "required": true
    },
    "password": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "orders": {
      "type": "hasMany",
      "model": "ShopifyOrder",
      "foreignKey": ""
    },
    "user": {
      "type": "belongsTo",
      "model": "ApiUser",
      "foreignKey": "userid"
    }
  },
  "acls": [],
  "methods": {}
}

当我运行自动迁移时,会创建shopifyaccount表,但它看起来很奇怪:

  Column       |  Type   |                          Modifiers                          
     

------------------- + --------- + ----------------- --------------------------------------------

     

api_key |文字|不为空

     

密码|文字|不为空

     

id |整数| not null default nextval(' shopifyaccount_id_seq' :: regclass)

     

userid | uuid |

     

apiuserid | uuid |

     

索引:

     

" shopifyaccount_pkey" PRIMARY KEY,btree(id)

为什么要创建2个这样命名的列?即使我尝试指定外键是" userid",它仍然会创建apiuserid列。插入将永远不会更新apiuserid列,但它将更新userid列。然后在加入时,它将尝试加入apiuserid。我做错了什么?

1 个答案:

答案 0 :(得分:0)

所以...似乎需要在ApiUser和ShopifyAccount中的两个地方都指定“foreignkey”:

{
  "name": "ApiUser",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "postgresql": {
      "table": "users"
    },
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "type": "string",
      "id": true,
      "required": true,
      "defaultFn": "uuid",
      "postgresql": {
        "dataType": "uuid"
      }
    },
    "email": {
      "type": "string",
    ...
  "relations": {
    "shopifyAccounts": {
      "type": "hasOne",
      "model": "ShopifyAccount",
      "foreignKey": "userid"
    }
  },
  "acls": [],
  "methods": {}
}