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

如何将bookings查询的结果作为timeslots查询中_nin过滤器的参数

如何将bookings查询的结果作为timeslots查询中_nin过滤器的参数

嘿,这个问题我之前也碰到过!从你给出的查询语法来看,应该是用Hasura GraphQL对吧?这里有两种靠谱的解决办法,我给你详细拆解下:

方法一:使用Hasura子查询(推荐,一次请求搞定)

Hasura支持在where条件里直接嵌套子查询,不用额外的客户端逻辑,就能把bookings表的timeslot_id结果直接作为timeslots查询的_nin过滤参数。

修改后的完整查询如下:

query GetAvailableTimeslots {
  timeslots(
    where: {
      service_provider: {phone: {_eq: "+14155238886"}},
      service: {name: {_like: "%mecanic%"}},
      date_service: {_eq: "2023-03-27"},
      id: {_nin: { _select: "timeslot_id", _from: "bookings" }}
    }
  ) {
    date_service
    id
    service_id
    service_provider_id
    start_time
    end_time
    service {
      name
    }
  }
}

这里的核心是在_nin里用_select指定要从bookings表取的字段(timeslot_id),再用_from指定数据源表名,Hasura会自动把bookings中所有的timeslot_id收集起来,作为排除条件过滤timeslots。

方法二:客户端分两次请求(适合需要额外处理数据的场景)

如果需要在客户端对bookings返回的timeslot_id做额外处理(比如去重、过滤空值),可以分两步走:

  1. 先查询bookings拿到所有已预订的timeslot_id列表;
  2. 把这个列表作为变量传入timeslots查询的_nin参数中。

下面是JavaScript的示例代码:

// 第一步:获取已预订的timeslot_id列表
async function getBookedTimeslotIds() {
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: `
        query GetBookedTimeslots {
          bookings {
            timeslot_id
          }
        }
      `
    })
  });
  const data = await response.json();
  // 可以在这里做额外处理,比如去重、过滤null
  return data.data.bookings.map(booking => booking.timeslot_id).filter(id => id);
}

// 第二步:查询可用的timeslots
async function getAvailableTimeslots() {
  const bookedIds = await getBookedTimeslotIds();
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: `
        query GetAvailableTimeslots($bookedIds: [Int!]!) {
          timeslots(
            where: {
              service_provider: {phone: {_eq: "+14155238886"}},
              service: {name: {_like: "%mecanic%"}},
              date_service: {_eq: "2023-03-27"},
              id: {_nin: $bookedIds}
            }
          ) {
            date_service
            id
            service_id
            service_provider_id
            start_time
            end_time
            service {
              name
            }
          }
        }
      `,
      variables: { bookedIds }
    })
  });
  const data = await response.json();
  return data.data.timeslots;
}

备注:内容来源于stack exchange,提问作者J. Viégas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 10:44:50