Yesod: Getting a database entity by ID from an Int

后端 未结 3 2126
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 07:00

I\'m new to both Haskell and Yesod, and am trying to build a simple web application that can answer queries from an external API. I have built a parser (using Parsec), that

3条回答
  •  盖世英雄少女心
    2020-12-14 07:25

    Even if the answer can already be found in the comments, I would like to give a complete example.

    Assuming we have a Person Model, the following function returns a record for the persion with the given ID (if it exists):

    import Database.Persist.Types (PersistValue(PersistInt64))
    
    getByIntId :: Integral i => i -> Handler (Maybe Person)
    getByIntId i = runDB $ get $ Key $ PersistInt64 (fromIntegral i)
    

    The import is needed to let us construct the persist-version of an integer. fromIntegral converts any integer to the expected type Int64.

    Update: Since Yesod 1.2 PersistValue lives in the module Database.Persist.Types, before 1.2 it was Database.Persist.Store (API Documentation).

    Update 2: Since Persistent 2.0.2 there are two build-in functions to convert from/to database keys: toSqlKey and fromSqlKey (API Documentation, see answer by hhefesto for an example).

提交回复
热议问题