FindById in persistent

6 views
Skip to first unread message

Sudip Bhattarai

unread,
Nov 30, 2020, 1:09:49 AM11/30/20
to Yesod Web Framework

I don't know if it's just a beginner problem, or insufficiency of the documentation, The getById is documented with following example.

personId <- insert $ Person "Michael" "Snoyman" 26
maybePerson <- get personId
case maybePerson of
Nothing -> liftIO $ putStrLn "Just kidding, not really there"
Just
person -> liftIO $ print person



But  how do i do say  get person having id of 3?

maybePerson <- get 3  {- this doesn' twork with type mismatch-}
maybePerson <- get (PersonId 3)  {- this also doesn't work -}

Sudip Bhattarai

unread,
Nov 30, 2020, 1:09:49 AM11/30/20
to Yesod Web Framework
For schema below, How do I find a person by id 3?

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
firstName String
lastName String
age Int Maybe
PersonName firstName lastName
deriving Show
|]

the Example provided in the persistent book says

personId <- insert $ Person "Michael" "Snoyman" 26
maybePerson
<- get personId

But 
maybePerson <- get 3  will not compile.

Michael Snoyman

unread,
Nov 30, 2020, 2:14:04 AM11/30/20
to yeso...@googlegroups.com
This section of the book gives a bit more information:


You can use the toSqlKey function to help with this:


--
You received this message because you are subscribed to the Google Groups "Yesod Web Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to yesodweb+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/yesodweb/8736e9a5-11f5-45de-8794-be0c6f3149ebn%40googlegroups.com.

jsch...@gmail.com

unread,
Dec 23, 2020, 5:58:00 PM12/23/20
to Yesod Web Framework
I just want to add some sentences because understanding this helped me once. Maybe it's already totally clear to you:

Often you don't need to convert from Int to PersonId.

For example in routes, you directly write
/persons/#PersonId
instead of
/persons/#Int

And if another entity points to a Person, than the type should also be PersonId instead of Int.
Reply all
Reply to author
Forward
0 new messages