Slick left outer join fetching whole joined row as option

后端 未结 3 1867
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 10:48

My join looks like this:

def byIdWithImage = for {
    userId <- Parameters[Long]
    (user, image) <- Users leftJoin RemoteImages on (_.imageId === _.id)          


        
3条回答
  •  醉梦人生
    2021-02-03 11:30

    Off the top of my head, I'd use a custom mapped projection. Something like this:

    case class RemoteImage(id: Long, url: URL)
    
    def byIdWithImage = for {
        userId <- Parameters[Long]
        (user, image) <- Users leftJoin RemoteImages on (_.imageId === _.id) if user.id === userId
    } yield (user, maybeRemoteImage(image.id.? ~ image.url.?))
    
    def maybeRemoteImage(p: Projection2[Option[Long], Option[URL]]) = p <> ( 
      for { id <- _: Option[Long]; url <- _: Option[URL] } yield RemoteImage(id, url),
      (_: Option[RemoteImage]) map (i => (Some(i id), Some(i url)))
    )
    

    Using scalaz (and its ApplicativeBuilder) should help reduce some of that boilerplate.

提交回复
热议问题