Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何在Slick中定义可选外键?_Scala_Slick - Fatal编程技术网

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

Scala 如何在Slick中定义可选外键?,scala,slick,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

我有一张这样的桌子:

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.
 ...
}
我的案例类别是:

case class AddressRow(
  id: Option[Int] = None,
  street: String,
  number: String,
  zipcode: String,
  city: String,
  country: String,
  geoLocationId: Option[Int])
正如您所注意到的,地理位置是一个可选的外键

在我的外键定义中,我找不到任何方法来描述这个“可选的”

我试过:

  def geoLocation = foreignKey("fk_geo_location", geoLocationId.asColumnOf[Option[Int]], GeoLocations)(_.id)
但我收到:

原因:scala.slick.SlickException:无法使用列应用 外键约束中的函数强制转换(仅指定命名列) 允许的)


有人有什么建议吗?

我不认为你想用外键来实现。 检查并从光滑的文件

请注意带有
leftJoin
的示例:

val explicitLeftOuterJoin = for {
  (c, s) <- Coffees leftJoin Suppliers on (_.supID === _.id)
} yield (c.name, s.name.?)
然后,您可以映射该查询的结果,以便返回实际的
地址
实例,并使用
选项[GeoLocation]
。这就是我在文档中链接“用户定义类型”的原因。。。这对我来说是一个新特性(我熟悉ScalaQuery,它是Slick的前一个化身),但它看起来相当有前途。

尝试以下方法:

def geoLocationId = column[Option[Int]]("geo_location_id")
//Foreign Key
def geoLocation = foreignKey("fk_geo_location", geoLocationId, GeoLocations)(_.id.?)
geoLocationId
现在是
选项[Int]
的一列,因此不再需要
O.Nullable
(.id.?)
地理位置
作为选项返回,如果为空则返回

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