clojuresqlkorma

How to I correctly define a foreign key for a SQLKorma entity?


When I run a simple query with the below entity configuration. SqlKorma generates a query and tried to join table_b with table_a, but it is using a field which doesn't exist?

SELECT "table_a"."token", "table_a"."first-name", "table_a"."last-name", "table_b"."item" FROM ("table_a" LEFT JOIN "table_b" ON "table_b"."table_a_id" = "table_b"."token" 

I have specified in the configuration the correct foreign key yet sqlKorma still tried to join on table_a_id?

(declare table_a table_b)

(korma/defentity table_a
                 (korma/pk :token)
                 (korma/database db)
                 (korma/table :table_a)
                 (korma/has-one table_b))

(korma/defentity table_b
                 (korma/pk :token)
                 (korma/database db)
                 (korma/table :table_b)
                 (korma/belongs-to table_a {:fk :token}))

If I set table_b PK to table_a_id then the query will work, but I want to use token as the PK.


Solution

  • I needed to add the foreign key on the other side like this:

    (declare table_a table_b)
    
    (korma/defentity table_a
                     (korma/pk :token)
                     (korma/database db)
                     (korma/table :table_a)
                     (korma/has-one table_b {:fk :token}))
    
    (korma/defentity table_b
                     (korma/pk :token)
                     (korma/database db)
                     (korma/table :table_b)
                     (korma/belongs-to table_a {:fk :token}))