如何跟踪刚刚添加到数据库中的内容的实体 ID?

How to keep track of the entity id for the stuff that was just added to the db?

在 html-post 页面上,用户可以输入各种字段并点击提交,

我的 router.clj 代码看起来像

 (POST "/postGO" [ post-title post-input post-tags :as request ]
    (def email (get-in request [:session :ze-auth-email]))
      ;; connect to datomic and write in the request
    (dbm/add-ze-post post-title post-input post-tags email) ;; db insert

    {:status 200, 
     :body "successfully added the post to the database", 
     :headers {"Content-Type" "text/plain"}}) ;;generic return page

它运行良好,但我想在之后将用户重定向到一个可以显示他们上传的页面 post。为此,获得刚刚交易的实体的 eid 将非常有帮助。

;; code from my dbm file for playing directly with the database
;; id est: the db transact code
(defn add-ze-blurb [title, content, tags, useremail]
  (d/transact conn [{:db/id (d/tempid :db.part/user),
                     :post/title title,
                     :post/content content,
                     :post/tag tags,
                     :author/email useremail}]))

有什么方法可以在成功添加到数据库后立即获得 datomic return eid,还是我应该立即使用另一个查询来确保它在那里?

对于简单的情况,只需取消引用 d/transact 返回的未来并使用 :tx-data。完整示例:

(require '[datomic.api :refer [db q] :as d])
(def uri "datomic:mem://test")
(d/create-database uri)

(def conn (d/connect uri))
(def schema [{:db/id (d/tempid :db.part/db)
              :db/ident :foo
              :db/valueType :db.type/string
              :db/cardinality :db.cardinality/one
              :db.install/_attribute :db.part/db}])
@(d/transact conn schema)

(def tempid (d/tempid :db.part/user))
(def tx [{:db/id tempid :foo "bar"}])
(def result @(d/transact conn tx)) ;; 
(def eid (:e (second (:tx-data result))))
(assert (= "bar" (:foo (d/entity (db conn) eid))))

您也可以使用 d/resolve-tempid:

(def eid (d/resolve-tempid (db conn) (:tempids result) tempid))
(assert (= "bar" (:foo (d/entity (db conn) eid))))

Datomic documentation 中所述,取消引用后,交易者将应用交易,返回的数据反映数据库的新值。