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

如何指定participants对象首个键为用户ID以正确关联查询用户数据

解决方案

原代码错误原因

ReferenceManyField的作用是查询目标资源(你这里指定的是users)中target字段值等于当前会话记录ID的所有数据,你配置的target="participants"相当于去用户接口查询participants字段等于当前会话ID的用户,和你实际的存储逻辑完全相反,自然无法正确匹配参会用户。

实现代码

你的participants字段是以用户ID为键的对象,只需要先提取对象的键作为用户ID,再用ReferenceField关联查询即可,分两种场景:

仅取首个参会用户

import { ReferenceField, ChipField, useRecordContext } from 'react-admin';

const FirstParticipantField = () => {
  const record = useRecordContext();
  // 无参会者时返回空
  if (!record?.participants) return null;
  // 提取participants对象的第一个键作为用户ID
  const userId = Object.keys(record.participants)[0];
  return (
    <ReferenceField reference="users" id={userId} link="show">
      <ChipField source="name" />
    </ReferenceField>
  );
};

使用时直接在列表/详情页引入组件即可:

<FirstParticipantField label="用户" />

取所有参会用户

如果需要展示所有参会人,只需要循环所有用户ID即可:

import { ReferenceField, ChipField, useRecordContext } from 'react-admin';
import { Stack } from '@mui/material';

const AllParticipantsField = () => {
  const record = useRecordContext();
  if (!record?.participants) return null;
  // 提取所有用户ID
  const userIds = Object.keys(record.participants);
  return (
    <Stack direction="row" spacing={1}>
      {userIds.map(userId => (
        <ReferenceField key={userId} reference="users" id={userId} link="show">
          <ChipField source="name" />
        </ReferenceField>
      ))}
    </Stack>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:42:02