2013-03-12 12 views
6

私はこのようなテーブルがあります:私はできませんSlickでオプションの外部キーを定義する方法は?

....

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

あなたはジオロケーションは、オプションの外部キーである気づくのよう:私の場合クラスがある

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. 
... 
} 

を私の外来キーの定義でこれを "オプション"と記述する方法を見つける。

私は次のように試してみた:

def geoLocation = foreignKey("fk_geo_location", geoLocationId.asColumnOf[Option[Int]], GeoLocations)(_.id) 

が、私が受け取る:

によって引き起こさ

:scala.slick.SlickException:のみという名前の外部キー制約にキャスト 機能(適用列を使用することはできません列は です)

誰かが提案をしていますか?

答えて

3

あなたがしようとしていることは、外部キーを使用して達成できるとは思いません。 Slick docsからjoininguser defined typesを調べてください。 leftJoin

注意例:あなたはあなたのAddressesのすべてを照会したい場合

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

だから、あなたはあなたがその後、マップすることができ

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

ようなもので開始したいと思います実際のAddressインスタンスを取得し、Option[GeoLocation]で完了するように、そのクエリの結果を返します。だからこそ私はドキュメントの "ユーザー定義型"をリンクしています。これは新機能です(私はSlickの前身であるScalaQueryに精通していました)が、かなり有望です。

10

は、以下のことを試してみてください。それがnullだった場合

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の柱です。

+0

ああ、それは動作します。ありがとう。 – liutao

関連する問題