使用“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
有人可以简单解释直通模型是什么吗? 一些例子将不胜感激。
答案 0 :(得分:15)
通过模型通常用于many to many
数据关系。
例如,您有3个模型:
User
包含id
和username
字段; Team
包含id
和teamName
字段; TeamMember
,其中包含userId
和teamId
个字段。 User
可以是许多Team
的成员,而Team
可以有许多User
。 User
和Team
的关系将存储在TeamMember
。
要在环回中创建many to many
关系,您必须将relation
属性添加到模型定义文件中:
User
模型定义文件(user.json)
"relations": {
"teams": {
"type": "hasMany",
"model": "team",
"foreignKey": "userId",
"through": "teamMember"
}
}
Team
模型定义文件
"relations": {
"users": {
"type": "hasMany",
"model": "user",
"foreignKey": "teamId",
"through": "teamMember"
}
}
TeamMember
模型定义文件
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": "userId"
},
"team": {
"type": "belongsTo",
"model": "team",
"foreignKey": "teamId"
}
}
您还可以在StrongLoop docs
上找到有关“直通模型”的信息