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

Directus 9.21.2版本关联子模型字段验证失效问题反馈

解决Directus 9.21.2中Parent端多对多关联Child字段验证失效问题

问题背景

在Directus 9.10.0中,可在Parent实体的多对多字段验证标签页配置关联Child字段的验证规则(如标题非空),但升级至9.21.2后该配置失效,允许创建标题为空的Child数据。需求是保持在Parent端配置验证,以便为同一个Child实体的不同关联字段设置不同规则。

解决方案

1. 确认版本变更的验证逻辑调整

Directus 9.10.0到9.21.2的版本迭代中,调整了关联字段验证的生效范围:原版本中多对多字段的验证会穿透到关联实体的字段,新版本中这类验证仅作用于关联关系本身(如是否必填关联项),不再校验关联实体的字段内容。

2. 自定义后端Hook实现针对性验证

通过编写Directus自定义Hook,在Parent实体的创建/更新操作时,主动校验关联Child实体的字段是否符合规则,具体代码示例如下:

module.exports = function registerHook({ action }, { services }) {
  const { ItemsService } = services;

  // 监听Parent集合的创建与更新操作
  ['items.create', 'items.update'].forEach((event) => {
    action(event, async (payload, meta) => {
      // 仅处理Parent集合的操作
      if (meta.collection !== 'parent') return;

      // 获取当前操作中关联的Child ID列表(替换为你的多对多字段名,如`childs`)
      const childIds = payload.childs || [];
      if (!childIds.length) return;

      // 初始化Child实体的服务实例
      const childService = new ItemsService('child', { 
        schema: meta.schema, 
        accountability: meta.accountability 
      });
      // 批量读取关联的Child数据
      const children = await childService.readMany(childIds);

      // 校验每个Child的标题是否非空
      const invalidChildIds = children
        .filter(child => !child.title?.trim())
        .map(child => child.id);

      if (invalidChildIds.length > 0) {
        throw new Error(`ID为${invalidChildIds.join(', ')}的Child数据标题不能为空`);
      }
    });
  });
};

将上述代码保存为Hook文件(如validate-parent-child.js),放入Directus项目的extensions/hooks/目录下,重启Directus服务即可生效。若需为不同的多对多关联字段设置不同规则,可复制该Hook并修改字段名和校验逻辑。

3. 前端辅助验证(可选)

若需要在界面层即时提示用户,可在Parent实体的多对多字段配置中,使用自定义界面组件或添加前端验证脚本,但后端Hook验证仍是核心保障,避免绕过前端操作的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:21:28