我有一個想法實體和IdeaType實體(它就像電腦和公司,在計算機數據庫的例子)
case class IdeaTest(
val id: Pk[Long] = NotAssigned,
val name: String = "unknown idea",
val description: String = "no description",
val kind: IdeaType = IdeaType()
)
case class IdeaType (
val id: Pk[Long] = NotAssigned,
val name: String = "unknown idea type",
val description: String = "no description"
)
我定義了一個TypeParser
val typeParser: RowParser[IdeaType] = {
get[Pk[Long]]("idea_type.id") ~
get[String]("idea_type.name") ~
get[String]("idea_type.description") map {
case id~name~description => IdeaType(
id, name, description
)
}
}
的第一件事情我嘗試是:
val ideaParser: RowParser[IdeaTest] = {
get[Pk[Long]]("idea.id") ~
get[String]("idea.name") ~
get[String]("idea.description") ~
typeParser map {
case id~name~description~ideaType => IdeaTest(
id, name, description, ideaType
)
}
}
即使它編譯好,它總是有問題加載ideaType。
最後,我不得不沒有ideaType限定ideaParser並用typeParser構成它:
val typeParser: RowParser[IdeaType] = {
get[Pk[Long]]("idea_type.id") ~
get[String]("idea_type.name") ~
get[String]("idea_type.description") map {
case id~name~description => IdeaType(
id, name, description
)
}
}
val ideaWithTypeParser = ideaParser ~ typeParser map {
case idea~kind => (idea.copy(kind=kind))
}
,這是用它的代碼:唯一的麻煩我
def ideaById(id: Long): Option[IdeaTest] = {
DB.withConnection { implicit connection =>
SQL("""
select * from
idea inner join idea_type
on idea.idea_type_id = idea_type.id
where idea.id = {id}""").
on('id -> id).
as(ideaParser.singleOpt)
}
}
請參閱,是否必須以不一致的狀態創建IdeaTest對象(不含ideaType),然後使用正確的IdeaType將其複製到另一個實例。
這個答案非常有用,有助於鞏固我對編寫解析器的理解,謝謝! – EdgeCaseBerg