Insert many-to-many relations

22 views
Skip to first unread message

Yury Yantsevich

unread,
Aug 27, 2017, 5:48:11 PM8/27/17
to Korma
Hi all!

I have 2 models with many-to-many relationship like the next:

(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))

I want to insert into both new data and make a relationship in the same transaction

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

Unfortunately, it doesn't work this way. None of insertions into users or organisations work. Is it possible to do something like that in Korma?

I try to get something like the next Postgresql statement:

WITH new_user AS (
  INSERT INTO users (email)
  VALUES ('jo...@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 *;

Thanks,
Yury
Reply all
Reply to author
Forward
0 new messages