Drizzle ORM中with操作符关联表加WHERE子句报错求助
解决方案
问题原因
你在关联查询的with选项中直接使用了eq表达式作为where的值,但Drizzle ORM要求关联查询的where必须是一个回调函数,接收关联表对象和操作符集合作为参数,这样TypeScript才能正确推断类型,避免属性不存在的错误。
方案1:修正关联查询的where写法
将with.portfolio.where改为回调函数形式,让Drizzle正确识别关联表的字段类型:
const itemExists = await db.query.portfolioItems.findFirst({ where: (portfolioItems, { eq, and }) => and( eq(portfolioItems.id, validatedParams.item_id), eq(portfolioItems.portfolioId, validatedParams.id) ), with: { portfolio: { // 改为回调函数,参数为关联表和操作符 where: (portfolios, { eq }) => eq(portfolios.userId, userId), } } })
方案2:将关联过滤移至主查询where(更推荐)
如果你的需求只是验证该portfolioItem属于指定用户的portfolio,不需要返回过滤后的portfolio数据,可以用exists子查询将关联条件整合到主查询的where中,逻辑更清晰:
const itemExists = await db.query.portfolioItems.findFirst({ where: (portfolioItems, { eq, and, exists }) => and( eq(portfolioItems.id, validatedParams.item_id), eq(portfolioItems.portfolioId, validatedParams.id), // 用exists验证关联的portfolio属于当前用户 exists( db.select().from(portfolios).where( and( eq(portfolios.id, portfolioItems.portfolioId), eq(portfolios.userId, userId) ) ) ) ), // 如需返回portfolio数据,保留with: { portfolio: true }即可 with: { portfolio: true } })
额外提示
确保你的Drizzle ORM版本是最新的,旧版本可能对关联查询的类型支持不完善。可以通过npm update drizzle-orm pg更新依赖。
内容的提问来源于stack exchange,提问作者Simo D.
相关产品推荐
相关产品推荐

