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"
}

你可能感兴趣的:(Model Relations)