简体   繁体   中英

Update a row with specific ID in Esqueleto

I can change a field of a row with entryId in Esqueleto like this:

  update $ \entry -> do
    set entry [ EntryFoo =. val bar ]
    where_ (entry ^. EntryId ==. val entryId)

However, writing it all the time gets annoying. I'd like to be able to write something like this:

  updateById entryId $ \entry ->
    set entry [ EntryFoo =. val bar ]

I tried to write this helper by myself, but found that I don't know how to write ^. EntryId ^. EntryId in a generic way (ie a way that would work for any entry types). Is it possible? Or am I missing something and updateById already exists in Esqueleto?

I am definitely no expert on esqueleto, but I would guess:

updateById entryId upd = update $ \entry -> do
                           upd entry
                           where_ (entry ^. EntryId ==. val entryId)

should solve the problem.

For any Entity , ^. EntityId ^. EntityId can be written as ^. persistIdField ^. persistIdField (the persistIdField field is a method of the PersistEntity class). Thus, your function can be written like this:

updateById
  :: (E.PersistEntityBackend val ~ E.SqlBackend,
      MonadIO m, E.PersistEntity val)
  => Key val
  -> (E.SqlExpr (E.Entity val) -> E.SqlQuery a)
  -> E.SqlWriteT m ()
updateById entryId upd = E.update $ \entry -> do
  upd entry
  E.where_ (entry E.^. E.persistIdField ==. E.val entryId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM