使用Korma在一个事务中插入多对多关系

时间:2017-08-28 08:53:31

标签: sql clojure korma

我有2个模型,具有多对多关系,如下一个:

(declare organisations)

(defentity users
  (many-to-many organisations :users_organisations
                {:lfk :user_id, :rfk :organisation_id}))

(defentity organisations
  (many-to-many users :users_organisations
                {:lfk :organisation_id, :rfk :user_id}))

(defentity users-organisations
  (table :users_organisations))

我想在两个模型中插入行,并在同一个事务中创建关系记录

(transaction
  (let [usr (insert users (values {:email "john@mail.me"}))
        org (insert organisations (values {:title "My Co."}))]
    (insert users-organisation
            (values {:user_id (:id usr)
                     :organisation_id (:id org)}))))

不幸的是,这种方式不起作用。用户或组织中的任何插入都不起作用。是不是可以在Korma做类似的事情?

我尝试实现的是下一个Postgresql语句:

WITH new_user AS (
  INSERT INTO users (email)
  VALUES ('john@mail.me')
  RETURNING id
), new_org AS (
  INSERT INTO organisations (title)
  VALUES ('My Co.')
  RETURNING id
)
INSERT INTO users_organisations (user_id, organisation_id)
VALUES ((SELECT id FROM new_user), (SELECT id FROM new_org))
RETURNING *;

提前感谢您的帮助!

0 个答案:

没有答案