渴望使用Anorm获取

时间:2014-07-30 11:28:43

标签: scala playframework anorm playframework-2.3

我正在尝试使用 Anorm 进行急切的抓取,这是像https://gist.github.com/guillaumebort/2788715这样的懒人抓取

package models

import java.util.Date

import anorm._
import anorm.SqlParser._
import play.api.db.DB
import play.api.Play.current

// table users
case class User(id: Option[Long] = None, firstName: Option[String], lastName: Option[String]) {

  // mismatch types Set[Nicknames] and List[Nicknames] because * returns List
  lazy val nickNames: Set[Nicknames] = DB.withConnection { implicit connection =>
    SQL"""
       SELECT * FROM nicknames
       JOIN types t ON nicknames.type_id = t.id
       JOIN events e ON nicknames.events_id = e.id
       WHERE user.id = $id
    """.as(Nickname.withTypeAndEvents.*)
  }
}

object User {
  val simple = {
    get[Option[Long]]("users.id") ~
      get[Option[String]]("users.first_name") ~
      get[Option[String]]("users.last_name") map {
      case id ~ firstName ~ lastName => User(id, firstName, lastName)
    }
  }

  def findById(id: Long): Option[User] = DB.withConnection { implicit connection =>
    SQL"SELECT * FROM users WHERE id = $id".as(simple.singleOpt)
  }
}

// table nicknames
case class Nickname(id: Option[Long] = None, name: Option[String], startDate: Option[Date],
                    nType: Option[NickType] = None,
                    user: Option[User] = None,
                    events: Option[Set[Event]] = None) // I use Set here to remove duplicates

object Nickname {
  val simple = {
    get[Option[Long]]("nicknames.id") ~
      get[Option[String]]("nicknames.name") ~
      get[Option[Date]]("nicknames.start_date") map {
      case id ~ name ~ startDate => Nickname(id, name, startDate)
    }
  }

  val withTypeAndUser = simple ~ NickType.simple ~ User.simple map {
    case nick ~ nType ~ user => nick.copy(nType = Some(nType), user = Some(user))
  }

  val withTypeAndEvents = withTypeAndUser ~ Event.simple map {
                                         // it's wrong I think
    case nick ~ event => nick.copy(events = Some(Set(event))) 
  }
}

// table types
case class NickType(id: Option[Long] = None, name: Option[String])

object NickType {
  val simple = get[Option[Long]]("types.id") ~ get[Option[String]]("types.name") map {
    case id ~ name => NickType(id, name)
  }
}

// table events
case class Event(id: Option[Long] = None, regDate: Option[Date], description: Option[String],
                 user: Option[User] = None)

object Event {
  val simple = {
    get[Option[Long]]("events.id") ~
      get[Option[Date]]("events.reg_date") ~
      get[Option[String]]("events.description") map {
      case id ~ regDate ~ description => Event(id, regDate, description)
    }
  }
}

我需要findById使用昵称使用昵称返回我的用户而不是懒惰。

用户 - >昵称使用一对多关系

昵称 - >用户使用多对一关系加入列user_id

昵称 - >事件使用一对多关系

活动 - >昵称使用多对一关系加入列event_id

0 个答案:

没有答案