“通过模型”在环回中意味着什么?

时间:2015-08-02 14:49:59

标签: loopbackjs strongloop

使用“slc loopback:relation”定义关系时,会在最后一行提示“直通模型”。

? Select the model to create the relationship from: CoffeeShop
? Relation type: has many
? Choose a model to create a relationship with: Reviewer
? Enter the property name for the relation: reviewers
? Optionally enter a custom foreign key:
? Require a through model? No

有人可以简单解释直通模型是什么吗? 一些例子将不胜感激。

1 个答案:

答案 0 :(得分:15)

通过模型通常用于many to many数据关系。 例如,您有3个模型:

  1. User包含idusername字段;
  2. Team包含idteamName字段;
  3. TeamMember,其中包含userIdteamId个字段。
  4. User可以是许多Team的成员,而Team可以有许多UserUserTeam的关系将存储在TeamMember

    要在环回中创建many to many关系,您必须将relation属性添加到模型定义文件中:

    1. User模型定义文件(user.json)
    2. "relations": {
        "teams": {
          "type": "hasMany",
          "model": "team",
          "foreignKey": "userId",
          "through": "teamMember"
        }
      }

      1. Team模型定义文件
      2. "relations": {
          "users": {
            "type": "hasMany",
            "model": "user",
            "foreignKey": "teamId",
            "through": "teamMember"
          }
        }

        1. 并在TeamMember模型定义文件
        2. "relations": {
            "user": {
              "type": "belongsTo",
              "model": "user",
              "foreignKey": "userId"
            },
            "team": {
              "type": "belongsTo",
              "model": "team",
              "foreignKey": "teamId"
            }
          }

          您还可以在StrongLoop docs

          上找到有关“直通模型”的信息