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

Strapi查询rooms表时同时返回默认公共数据与认证用户私有数据

解决方案

你的需求是同时返回无归属的公共默认房间、以及当前认证用户的私有房间,可直接使用Strapi的OR查询条件一次完成筛选,修正后代码如下:

Strapi v3 适用版本

async find(ctx) {
  const owner_id = ctx.state.user.id;

  // 单查询同时匹配两类符合要求的房间
  const targetRooms = await strapi.services.rooms.find({
    _or: [
      { owner_id: null }, // 匹配无归属的公共默认房间
      { owner_id: owner_id } // 匹配当前用户创建的私有房间
    ]
  });
  
  return sanitizeEntity(targetRooms, { model: strapi.models.rooms });
},

Strapi v4 适用版本

如果你的项目运行在Strapi v4环境,使用如下写法即可:

async find(ctx) {
  const owner_id = ctx.state.user.id;

  const targetRooms = await strapi.service('api::rooms.rooms').find({
    filters: {
      $or: [
        { owner_id: null },
        { owner_id: owner_id }
      ]
    }
  });
  
  return await this.sanitizeOutput(targetRooms, ctx);
},

逻辑说明

  • 直接通过OR查询过滤数据,无需分两次查询再合并,避免产生重复数据同时提升查询效率
  • 查询结果自动包含两类数据:所有用户通用的无owner_id公共房间、仅当前用户可见的自有私有房间
  • 不会返回其他用户创建的私有房间,完全符合业务要求

内容的提问来源于stack exchange,提问作者Raiyan Khalil Shuvo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:06:03