You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用GoJS修改家谱图实现子女与双亲双向关联?

解决GoJS家谱图双向亲子连接问题

1. 调整节点数据结构

orgChartEditor默认用parent字段维护上下级关系,家谱需要记录父母关联,给节点添加father和mother字段来分别存储对应父/母的节点key:

// 节点数据示例
const nodeDataArray = [
  { key: "father", name: "父亲" },
  { key: "mother", name: "母亲" },
  { key: "sister1", name: "姐妹1", father: "father", mother: "mother" }, // 双亲子女
  { key: "sister2", name: "姐妹2", father: "father" } // 仅父亲的子女
];

2. 手动生成双向连接数据

遍历节点数据,根据father和mother字段批量创建双向连接,替代模板默认的单向上下级连接:

const linkDataArray = [];
nodeDataArray.forEach(node => {
  // 生成子女与父亲的双向连接
  if (node.father) {
    linkDataArray.push({ from: node.key, to: node.father });
    linkDataArray.push({ from: node.father, to: node.key });
  }
  // 生成子女与母亲的双向连接(如果存在母亲关联)
  if (node.mother) {
    linkDataArray.push({ from: node.key, to: node.mother });
    linkDataArray.push({ from: node.mother, to: node.key });
  }
});

// 初始化图表模型,使用GraphLinksModel支持多对多连接
const myDiagram = new go.Diagram("myDiagramDiv", {
  // 图表基础配置,可保留orgChartEditor的部分样式
  allowDrop: true,
  "undoManager.isEnabled": true
});
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

3. 修改连线模板适配双向关系

如果需要直观区分亲子方向,可给连接添加分类并定制样式;也可以统一双向连线的视觉效果:

myDiagram.linkTemplate =
  new go.Link({
    routing: go.Link.AvoidsNodes,
    corner: 8,
    curve: go.Link.JumpOver
  })
    .add(new go.Shape({ strokeWidth: 2, stroke: "#444" }))
    .add(new go.Shape({ toArrow: "Standard", fill: "#444", stroke: null }));

// 若要区分父母→子女/子女→父母,可给连接加category字段,再通过模板映射不同样式
// 示例:给父母到子女的连接加category: "parentToChild",然后设置不同箭头

4. 禁用默认树形连接逻辑

关闭orgChartEditor模板中基于parent字段的自动树形连接,避免冲突:

// 清空端口关联属性,阻止自动生成树形连接
myDiagram.model.linkFromPortIdProperty = "";
myDiagram.model.linkToPortIdProperty = "";
// 确保不使用TreeModel,保持用GraphLinksModel处理多对多关系

5. 调整布局适配家谱结构

替换默认树形布局为分层布局,让父母节点在上、子女节点在下,更符合家谱视觉逻辑:

myDiagram.layout = new go.LayeredDigraphLayout({
  direction: 90, // 垂直方向布局
  layerSpacing: 120,
  columnSpacing: 60
});

完成以上调整后,即可实现:

  • 姐妹1与父亲、母亲均建立双向连接
  • 姐妹2仅与父亲建立双向连接
  • 所有亲子关系的双向连线正常展示

内容的提问来源于stack exchange,提问作者Prince Viktor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:24:50