对于具有默认字段的 Korma 实体,无法 SELECT COUNT(*)

Unable to SELECT COUNT(*) for Korma entity with default fields

我无法从我在 Korma 映射的实体 SELECT COUNT(*)

这是我的实体:

(declare users responses) (korma/defentity users (korma/entity-fields :id :slack_id :active :token :token_created) (korma/many-to-many responses :userresponses))

这是我尝试 SELECT COUNT(*):

(korma/select schema/users (korma/fields ["count(*)"]) (korma/where {:slack_id slack-id}))

我收到这个错误:

ERROR: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function at character 8 STATEMENT: SELECT "users"."id", "users"."slack_id", "users"."active", "users"."token", "users"."token_created", count(*) FROM "users" WHERE ("users"."slack_id" = )

看起来 Korma 包含了我的实体字段,尽管我在此查询中指定了 select 字段。我该如何覆盖它?

你不能自己覆盖它。 Korma 查询操作函数是 always additive,因此指定字段仅指定 附加 个字段。

要解决这个问题,您可以 rewrite this query to select against the users table itself 而不是 Korma 实体 users:

(korma/select :users
  (korma/fields ["count(*)"])
  (korma/where {:slack_id slack-id}))

但是你将不得不在 users 实体中没有定义任何其他内容的情况下凑合。

或者,您可以重写此实体以不定义任何 entity-fields,然后使用所需的默认字段定义此实体的包装版本:

(korma/defentity users-raw
  (korma/many-to-many responses :userresponses)))

(def users
  (korma/select
    users-raw
    (korma/fields [:id :slack_id :active :token :token_created])))```

然后你可以通过在这个"users"查询中添加with/where子句来编写你的普通查询,只有当你需要排除那些时才直接触摸users-raw字段:

(-> users (with ...) (where ...) (select))