[英]Inserting multiple rows in mysql using korma in clojure
我正在開發一個安靜的應用程序,它在后面使用 Clojure,在前面使用 Angular。 我有以下表格:客戶、訂單、項目、訂單項。 我正在使用 korma 與 MySql 數據庫進行通信。 當我對所有實體進行 CRUD 操作時,一切正常。 但我不知道如何在數據庫中插入多行? 我應該在 korma 中使用事務嗎?
(declare customer)
(declare customerorder)
(declare item)
(declare orderitems)
(schema/defschema OrderItem
{
:OrderItemId schema/Int
:OrderId schema/Int
:ItemId schema/Int
:Quantity schema/Int
})
(schema/defschema Customer
{
:CustomerId schema/Int
:Name schema/Str
:Contact schema/Str
})
(schema/defschema UpdateCustomer
{
:Name schema/Str
:Contact schema/Str
})
(schema/defschema NewCustomer
{
:Name schema/Str
:Contact schema/Str
})
(schema/defschema Order
{
:OrderId schema/Int
:CustomerId schema/Int
:PMethod schema/Str
:GTotal schema/Num
})
(schema/defschema Item
{
:ItemId schema/Int
:Name schema/Str
:Price schema/Num
})
(defentity customer
(pk :CustomerId)
(has-many customerorder {:fk :CustomerId})
(entity-fields :CustomerId :Name :Contact))
(defentity customerorder
(pk :OrderId)
(has-many orderitems {:fk :OrderId})
(belongs-to customer {:fk :CustomerId})
(entity-fields :PMethod :GTotal :OrderId)
)
(defentity item
(pk :ItemId)
(entity-fields :ItemId :Name :Price)
(has-many orderitems {:fk :ItemId}))
(defentity orderitems
(pk :OrderItemId)
(belongs-to item {:fk :ItemId})
(belongs-to customerorder {:fk :OrderId})
(entity-fields :OrderItemId :ItemId :Quantity))
這是我的查詢,用於選擇使用現金支付訂單和訂單項目的客戶:
(defn get-customersbypmethod [PMethod]
(select customerorder (with customer (with orderitems)) (where {:PMethod PMethod})))
我的問題是如何插入帶有訂單項的訂單?
Korma 文檔說明如下:
插入查詢使用函數(值)來添加記錄。 它接受單個映射或映射集合並返回第一個插入記錄的 id。
;; You can insert a single value:
(insert users
(values {:first "john" :last "doe"}))
;; or a collection of several:
(insert users
(values [{:first "john" :last "doe"}
{:first "jane" :last "doe"}]))
;; You can also compose inserts:
(def base (-> (insert* users)
(values {:first "john" :last "doe"})))
(-> base
(values {:first "jane" :last "doe"})
(insert))
;; Same thing as the collection insert
您可以簡單地使用 (transaction) 宏在 Korma 中進行交易,這確保在其中執行的所有查詢都是單個交易的一部分。 然后,您可以在必要時使用 (rollback) 函數強制事務回滾。
(transaction
(insert users
(values {:first "cool"}))
(insert address
(values {:address1 "cool"})))
(transaction
(if-not (valid?)
(rollback)
(do-complicated-query))
(when-not (is-rollback?)
(println "success!")))
希望這可以幫助。 Korma 是一個穩定且文檔齊全的庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.