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

Drizzle多对多查询中如何按timestamp对关联文章排序?

问题描述

已在Drizzle中配置好多对多关联并可执行查询,查询代码如下:

const category = await db.query.categoriesTable.findFirst({
    where: (categoriesTable, { eq }) =>
      eq(categoriesTable.id, params.categoryId),
    with: {
      articles: {
        with: {
          article: {
            columns: {
              title: true,
              content: true,
              timestamp: true,
            },
          },
        },
      },
    },
  });

尝试按timestamp对文章排序时,在articles的with配置中添加:

orderBy: (fields) => desc(fields.timestamp),

但TypeScript仅允许使用fields.articleId或fields.categoryId,请问问题出在哪?


解决方案

问题很明确:你操作的articles是多对多关系的中间关联表,这个表只有articleId和categoryId两个关联字段,根本没有timestamp——timestamp是存在关联的article主表里的。

要按文章的timestamp排序,得在articles的配置里,通过关联的article表来指定排序字段,修改后的代码如下:

const category = await db.query.categoriesTable.findFirst({
    where: (categoriesTable, { eq }) =>
      eq(categoriesTable.id, params.categoryId),
    with: {
      articles: {
        with: {
          article: {
            columns: {
              title: true,
              content: true,
              timestamp: true,
            },
          },
        },
        // 通过关联的article表指定排序字段
        orderBy: (fields, { desc }) => desc(fields.article.timestamp),
      },
    },
  });

这里的fields.article就是你在with中关联的article表,通过它就能访问到timestamp字段,TypeScript也会正确识别类型。如果需要正序排序,把desc换成asc即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 00:12:14