Loopback:Through关联无法正常工作问题排查
嘿,我一眼就瞅见你这个LoopBack模型配置里可能踩了多对多关联的常见小坑!咱们一步步捋:
1. 外键配置搞反啦
你在client的teams关联里写的foreignKey: "teamId"是错的——这个字段应该指向client表在中间表(client-team)里的外键,也就是clientId才对!毕竟中间表是用来关联client和team的,client这边的关联要绑定自己在中间表里的标识,而不是team的。
2. 中间表命名建议用驼峰
虽然JSON里允许用client-team这种带连字符的模型名,但在后续代码里引用(比如app.models['client-team'])会很麻烦,LoopBack官方更推荐驼峰式命名,比如改成clientTeam,可读性和实用性都更强。
3. 多对多关联要两边配置
光在client这边加hasMany through还不够,team模型里也得对应加上关联配置,不然双向关联会出问题,查询的时候可能拿不到预期的关联数据。
修正后的client.json示例
{ "name": "client", "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "properties": { "name": { "type": "string", "required": true } }, "validations": [], "relations": { "teams": { "type": "hasMany", "model": "team", "foreignKey": "clientId", "through": "clientTeam" } }, "acls": [] // 这里补全你原来的acls配置 }
额外提醒:检查中间表配置
中间表clientTeam(或你原来的client-team)里必须要有两个外键字段:clientId和teamId,分别关联client和team表的主键,示例配置大概是这样:
{ "name": "clientTeam", "base": "PersistedModel", "idInjection": true, "properties": { "clientId": { "type": "number", "required": true }, "teamId": { "type": "number", "required": true } }, "relations": { "client": { "type": "belongsTo", "model": "client", "foreignKey": "clientId" }, "team": { "type": "belongsTo", "model": "team", "foreignKey": "teamId" } } }
你把这些点修正后,再按官方文档测试关联查询,应该就能解决问题啦!
内容的提问来源于stack exchange,提问作者Demiro-FE-Architect
相关产品推荐
相关产品推荐

