Created
November 12, 2012 12:31
-
-
Save pedrofurla/4059099 to your computer and use it in GitHub Desktop.
Mapping oneToMany relationship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class Music(id:ID, title:String, isrc:String) | |
case class Compilation(id:ID=None, title:String, musics: List[Music], author:User /* TODO Either[DJ,Programmer]? */) | |
case class User(id:ID=None, name:String, email:String, password:String) | |
object Musics extends Table[Music]("music") { | |
def id = this.autoIncPk("id") | |
def title = this.string("title") | |
def isrc = this.string("isrc") | |
def * = id.? ~ title ~ isrc <> (Music, Music.unapply _) | |
def autoInc = title ~ isrc returning id | |
} | |
object Users extends Table[User]("user") { | |
def id = this.autoIncPk("id") | |
def name = this.string("name") | |
def email = this.string("email") | |
def password = this.string("password") | |
def * = id.? ~ name ~ email ~ password <> (User, User.unapply _) | |
} /* TODO all the other fields */ | |
object CompiledMusics extends Table[(Int, Int)]("compiled_music") { | |
def musicId = column[Int]("music_id") | |
def compilationId = column[Int]("compilation_id") | |
def musics = foreignKey(tableName+"_music_fk", musicId, Musics)(_.id) | |
def compilations = foreignKey(tableName+"_compilation_fk", compilationId, Compilations)(_.id) | |
def * = musicId ~ compilationId | |
} | |
object Compilations extends Table[Compilation]("compilation") { | |
def id = this.autoIncPk("id") | |
def title = this.string("title") | |
def authorId = column[Int]("author_id") | |
def authorFk = foreignKey(tableName+"_author_fk", authorId, Users)(_.id) | |
def musics = | |
for( cm <- CompiledMusics; if cm.compilationId === id; m <- cm.musics; if m.id === cm.musicId) yield m | |
def author = for(a <- Users; if a.id === authorId) yield a | |
/* How it should be | |
def * = id.? ~ title ~ musics ~ author <> | |
(Compilation, x => Compilation.unapply(x) map { x => (x._1,x._2) } ) | |
*/ | |
/* TODO ugly cheating/hacking to workaround my doubts regarding foreign keys! */ | |
def * = id.? ~ title <> | |
(Compilation(_,_,List(),null), x => Compilation.unapply(x) map { x => (x._1,x._2) } ) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment