[英]How to define optional foreign key in 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.
...
}
我的案例类在哪里:
case class AddressRow(
id: Option[Int] = None,
street: String,
number: String,
zipcode: String,
city: String,
country: String,
geoLocationId: Option[Int])
你注意到geoLocation是一个可选的外键....
我在外键定义中找不到任何描述这个“可选”的方法。
我尝试过:
def geoLocation = foreignKey("fk_geo_location", geoLocationId.asColumnOf[Option[Int]], GeoLocations)(_.id)
但我收到:
引起:scala.slick.SlickException:无法在外键约束中使用列Apply Function Cast(仅允许命名列)
有人有建议吗?
尝试以下方法:
def geoLocationId = column[Option[Int]]("geo_location_id")
//Foreign Key
def geoLocation = foreignKey("fk_geo_location", geoLocationId, GeoLocations)(_.id.?)
geoLocationId
现在是的一列Option[Int]
因此O.Nullable
不再需要(_.id.?)
返回GeoLocation
作为一个选项,或者None
如果它是零。
我不认为您尝试做的事情可以通过使用外键来实现。 从Slick文档中查看加入和用户定义的类型 。
请注意leftJoin
的示例:
val explicitLeftOuterJoin = for {
(c, s) <- Coffees leftJoin Suppliers on (_.supID === _.id)
} yield (c.name, s.name.?)
因此,如果您想查询所有Addresses
,则需要从类似的地方开始
val addressGeolocQuery = for {
(addr, loc) <- Addresses leftJoin GeoLocations on (_.geoLocationId === _.id)
} yield addr.id ~ loc.prop1.? ~ loc.prop2.? /*and so on*/
然后,您可以映射该查询的结果,以便返回实际的Address
实例,并使用Option[GeoLocation]
。 这就是为什么我在文档中链接“用户定义的类型”...这对我来说是一个新功能(我熟悉ScalaQuery,这是Slick之前的版本),但它看起来相当有前途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.