光滑左外连接获取整个连接行作为选项

Som*_*tik 11 scala left-join option slick

我的加入看起来像这样:

def byIdWithImage = for {
    userId <- Parameters[Long]
    (user, image) <- Users leftJoin RemoteImages on (_.imageId === _.id) if user.id === userId
} yield (user, image)
Run Code Online (Sandbox Code Playgroud)

但是当user.imageId为null时,浮动在运行时失败

[SlickException:读取列RemoteImage.url的NULL值]

将收益率改为

} yield (user, image.?)
Run Code Online (Sandbox Code Playgroud)

给我一个编译时异常,它只适用于各个列

找不到scala.slick.lifted.TypeMapper [image.type]类型的证据参数的隐含值

有没有不同的方法来完成我在这里尝试做的事情?(在单个查询中)

小智 8

在我的头顶,我会使用自定义映射投影.像这样的东西:

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)))
)
Run Code Online (Sandbox Code Playgroud)

使用scalaz(和它ApplicativeBuilder)应该有助于减少一些样板.

  • 谢谢,如果光滑为这种情况提供帮助,那将是很好的 (6认同)

Tar*_*sky 7

使用下面的代码,你可以这样说:yield(user,image.maybe)

case class RemoteImage(id: Long, url: URL)

class RemoteImages extends Table[RemoteImage]("RemoteImage") {
    def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
    def url = column[URL]("url", O.NotNull)
    def * = id.? ~ url <> (RemoteImage.apply _, RemoteImage.unapply _)

    def maybe = id.? ~ url.? <> (applyMaybe,unapplyBlank)

    val unapplyBlank = (c:Option[RemoteImage])=>None        

    val applyMaybe = (t: (Option[Long],Option[URL])) => t match {
        case (Some(id),Some(url)) => Some(RemoteImage(Some(id),url))
        case _ => None
    } 
}
Run Code Online (Sandbox Code Playgroud)