Model Relations

loopback 提供了四种models 之间的 联系, 分别为:

  1. belongs to 1 对1 的关系

B belongs to A , 那么 A 的主键一般为ID , 为B 中的外键值
在 B 中的relations配置为:
"A": {
"type": "belongsTo",
"model": "A",
"foreignKey": "AId"
}

  1. has one 1对1 的关系

A has one B 相当于 B belongs to A,不同的时在A中有一个字段 BID,关联到B 的主键ID
在 A中的relations配置为
"B": {
"type": "hasOne",
"model": "B",
"foreignKey": "id"
}

  1. has many 1 对N 的关系

A has Many B , A的主键ID,为B中的外键值
在A中的relations配置为
"Bs": {
"type": "hasMany",
"model": "B",
"foreignKey": "AId"
}

  1. has many through N 对 N 的关系

需要指定through 的model
如国A has many B through C , 那么A,B,C 中的配置如下

A中relations
"Bs": {
"type": "hasMany",
"model": "B",
"foreignKey": "AId",
"through": "C"
}

B中relations
"As": {
"type": "hasMany",
"model": "A",
"foreignKey": "BId",
"through": "C"
}

C中relations
"A": {
"type": "belongsTo",
"model": "A",
"foreignKey": "AId"
},
"B": {
"type": "belongsTo",
"model": "B",
"foreignKey": "BId"
}

  1. has and belongs to many N 对N 的关系, 不需要指定through的model

A has and belongs to many B,那么只需要在A 的relations中配置
"Bs": {
"type": "hasAndBelongsToMany",
"model": "B"
}
同时在B的relations中配置
"As": {
"type": "hasAndBelongsToMany",
"model": "A"
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,531评论 0 23
  • 姐妹是经常和你斗嘴,但却是最关心的人; 姐妹是经常载你面前损你,一有事确实第一个冲上去的人; 姐妹事经常骂你笨蛋,...
    倩爱人阅读 478评论 0 0
  • 云朵,是天空里浮沉的梦吧。 回过头来看这些沿途拍下的照片,日子又往前行进了几日。而那日出游也仿若是场大梦。或许是近...
    mo清夜无尘阅读 247评论 0 2
  • 风雨一程 不敢再挽着你前行 迷雾茫茫 不歇不停 我宁愿自己一人 也不愿你受痛苦的侵凌 无限柔情 只剩悲情 我该远行...
    映一梅阅读 232评论 0 3

友情链接更多精彩内容