我有一张这样的桌子:
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:无法使用在外键约束中强制转换的列应用函数(只允许指定列)引起的
有人有什么建议吗?
发布于 2013-03-12 21:57:22
我不认为你用外键就能完成你想做的事情。查看光滑文档中的接合和用户定义类型。
注意使用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,它是斯利克以前的化身),但它看上去相当有希望。
发布于 2013-09-24 13:03:55
尝试以下几点:
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,如果为null,则返回None。
https://stackoverflow.com/questions/15372495
复制相似问题