2012-10-02 34 views
6

我一直在看看computer-database sample,我注意到爲了重用計算機解析器,list方法使用Computer.withCompany解析器,它返回一個元組(電腦,公司)如何在scala使用playframework 2.0中的anorm解析器

在我處理的情況下,而不是一提到我想有一個計算機對象的計算機的ID,這樣

案例類計算機(ID:PK [長] = NotAssigned,名稱:字符串,介紹:選項[日期],終止:選項[日期],公司:公司)

所以我覺得我荷蘭國際集團如何實現類似下面的(它的seudocode,當然)

val simple = { 
    get[Pk[Long]]("computer.id") ~ 
    get[String]("computer.name") ~ 
    get[Option[Date]]("computer.introduced") ~ 
    get[Option[Date]]("computer.discontinued") ~ 
    get[Company]("company.*") map { 
    case id~name~introduced~discontinued~company => Computer(id, name, introduced, discontinued, company) 
    } 
} 

顯然,棘手的問題將是如何解決getCompany

任何想法???

回答

5

我有一個想法實體和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將其複製到另一個實例。

+1

這個答案非常有用,有助於鞏固我對編寫解析器的理解,謝謝! – EdgeCaseBerg