2011-06-19 55 views
1

我正在尋找一個與lift/mongodb一對一關係的簡單示例。 我能夠創建一個簡單的MongoRecord像這樣的:如何使用lift/mongodb創建一對一關係

class Blob extends MongoRecord[Blob] with MongoId[Blob] { 
    def meta = Blob 

    object name extends StringField[Blob](this,10) 

} 
object Blob extends Blob with MongoMetaRecord[Blob]{ 

} 

現在我想補充的父/子關係到斑點,我怎麼能做到這一點?

編輯:

我finaly找到如何解決我的問題(這guide我有很大幫助)。 下面是結果:

MongoRecord:

package code.model 

import net.liftweb.mongodb.record.{MongoMetaRecord, MongoRecord} 
import net.liftweb.record.field.StringField 
import net.liftweb.mongodb.record.field.{ObjectIdRefField, ObjectIdPk} 


class Blob extends MongoRecord[Blob] with ObjectIdPk[Blob]{ 

    def meta = Blob 

    object name extends StringField[Blob](this,10) 

    object child extends ObjectIdRefField(this,Blob) 

} 

object Blob extends Blob with MongoMetaRecord[Blob] 

這是我如何創建和讀取記錄:

package code.lib 

import net.liftweb.http._ 
import code.model.Blob 
import net.liftweb.common.{Full} 

object REST { 
    lazy val blob: LiftRules.DispatchPF = { 
    case Req("api" :: "blob" :: Nil, suffix, GetRequest) => { 
    () => { 
     val blobs = Blob.findAll.map(blob => { 

      val child = Blob.find(blob.child.is) 
      val childName = if (child.isDefined) child.open_!.name else "?" 

      <blob> 
      <id>{blob.id.is}</id> 
      <name>{blob.name}</name> 
      <child_name>{childName}</child_name> 
      </blob> 
     }) 

     Full(XmlResponse(<blobs>{blobs}</blobs>)) 
     } 
    } 
    case Req("api" :: "blob" :: Nil, suffix, PostRequest) => { 
    () => { 
     val randID = (scala.math.random * 999).toInt 

     val child = Blob.createRecord 
     child.name("child_" + randID) 
     child.save 

     val blob = Blob.createRecord 
     blob.name("blob_" + randID) 
     blob.child(child.id.is) 
     blob.save 

     Full(XmlResponse(<result>{blob.id.is}</result>)) 
     } 
    } 
    } 
} 

我'仍然不知道,如果是做正確的方法,所以: 歡迎任何評論!

回答