korma / Korma

Tasty SQL for Clojure.
http://sqlkorma.com
1.47k stars 222 forks source link

(with) and has-many relationships #260

Closed dvcrn closed 9 years ago

dvcrn commented 9 years ago

I am trying to follow the example on the website. My model:

(defentity user
  (table :user)
  (entity-fields
    :firstname
    :lastname
    :username
    :password
    :email
    :created_on
    :updated_on
  )
  (has-many poll))

(defentity poll
  (table :poll)
  (entity-fields
    :description
    :created_on
    :updated_on
  )
  (belongs-to user))

Code

  (sql-only 
    (select e/user
          (with e/poll)))

results in SELECT "user"."firstname", "user"."lastname", "user"."username", "user"."password", "user"."email", "user"."created_on", "user"."updated_on" FROM "user". Poll is being ignored.

The other way around, starting from poll and using (with e/user) is joining correctly.

poll has a user_id field, and poll.user_id = user.id.

Anything I missed here?

immoh commented 9 years ago

Polls are fetched using separate query. dry-run reveals this:

(dry-run (select user (with poll)))
dry run :: SELECT "user"."firstname", "user"."lastname", "user"."username", "user"."password", "user"."email", "user"."created_on", "user"."updated_on" FROM "user" :: []
dry run :: SELECT "poll"."description", "poll"."created_on", "poll"."updated_on" FROM "poll" WHERE ("poll"."user_id" = ?) :: [1]
=> ({:poll [{:user_id 1, :id 1}], :id 1})
dvcrn commented 9 years ago

@immoh Interesting. Thanks for the speedy answer!

Although even though it queries correctly, poll still stays empty even though there is definitely a row in the database.

I debugged a bit, and it turns out to be related to me using entity-fields. When removing the entity-fields definition in user, it displays everything correctly. When adding them again, it doesn't.

Any thoughts why this happens?

immoh commented 9 years ago

Currently it is required that the primary key of use is included in the query, otherwise child entities are not retrieved. There's an issue about it: #222

dvcrn commented 9 years ago

Yes, including the primary key solves this. Thank you!