如何在Slick中定义可选外键?

Cri*_*riu 8 scala slick

我有这样一张桌子:

object Addresses extends Table[AddressRow]("address") {
   def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def street = column[String]("street")
  def number = column[String]("number")
  def zipcode = column[String]("zipcode")
  def city = column[String]("city")
  def country = column[String]("country")
  def geoLocationId = column[Int]("geo_location_id", O.Nullable)

 // Foreign keys.
 def geoLocation = foreignKey("fk_geo_location", geoLocationId, GeoLocations)(_.id)

 // Rest of my code.
 ...
}
Run Code Online (Sandbox Code Playgroud)

我的案例类在哪里:

case class AddressRow(
  id: Option[Int] = None,
  street: String,
  number: String,
  zipcode: String,
  city: String,
  country: String,
  geoLocationId: Option[Int])
Run Code Online (Sandbox Code Playgroud)

你注意到geoLocation是一个可选的外键....

我在外键定义中找不到任何描述这个"可选"的方法.

我尝试过:

  def geoLocation = foreignKey("fk_geo_location", geoLocationId.asColumnOf[Option[Int]], GeoLocations)(_.id)
Run Code Online (Sandbox Code Playgroud)

但我收到:

引起:scala.slick.SlickException:无法在外键约束中使用列Apply Function Cast(仅允许命名列)

有人有建议吗?

Wel*_*ngr 16

尝试以下方法:

def geoLocationId = column[Option[Int]]("geo_location_id")
//Foreign Key
def geoLocation = foreignKey("fk_geo_location", geoLocationId, GeoLocations)(_.id.?)
Run Code Online (Sandbox Code Playgroud)

geoLocationId现在是一个列,Option[Int]因此O.Nullable不再需要 (_.id.?)返回GeoLocation作为选项,或者None如果它为null.


Dyl*_*lan 3

我不认为您想要做的事情可以通过使用外键来完成。从 Slick 文档中查看 连接用户定义的类型。

请注意带有 的示例leftJoin

val explicitLeftOuterJoin = for {
  (c, s) <- Coffees leftJoin Suppliers on (_.supID === _.id)
} yield (c.name, s.name.?)
Run Code Online (Sandbox Code Playgroud)

因此,如果您想查询所有的Addresses,您需要从类似的内容开始

val addressGeolocQuery = for {
  (addr, loc) <- Addresses leftJoin GeoLocations on (_.geoLocationId === _.id)
} yield addr.id ~ loc.prop1.? ~ loc.prop2.? /*and so on*/
Run Code Online (Sandbox Code Playgroud)

然后,您可以映射该查询的结果,以便返回一个实际的Address实例,并带有Option[GeoLocation]. 这就是为什么我在文档中链接了“用户定义类型”...这对我来说是一个新功能(我熟悉 ScalaQuery,它是 Slick 的前身),但它看起来相当有前途。