我想把数据模型映射到一个表单,如何转换数据类型



我使用slick2和playframework2。

我想将我的模型映射到来自的

我的型号是:

object Web extends App{
    case class Subject(id: Int, name:String, describe: String, sub_resource:String, addId:Long, recommand:Int, commentsum :Int, commentnumber: Int, userId: Int)
class Subjects(tag: Tag) extends Table[Subject](tag, "Subject") {
  def id=column[Int]("ID", O.PrimaryKey)
  def name=column[String]("Name")
  def describe=column[String]("describe")
  def sub_resource=column[String]("Resource")
  def keywords=column[String]("Keyword")
  def addID=column[Long]("Address")
  def recommandrate=column[Int]("Recommand")
  def commentsum=column[Int]("Sum_of_rate")
  def commentnumber=column[Int]("Rate_number")
  def userId=column[Int]("owner")
  def uniqueName = index("idx_grp_name", name, unique = true)
  def * = (id, name,sub_resource,keywords, addID, recommandrate, commentsum, commentnumber,userId)<> (Subject.tupled, Subject.unapply)
  def sub_res=foreignKey("sub_res_FK", sub_resource, resource)(_.link)
  def sub_address=foreignKey("sub_add_FK", addID, address)(_.id)
  def sub_user=foreignKey("sub_user_FK", userId, user)(_.id)
}
val subject = TableQuery[Subject]
}

我想把它映射到一个dataForm:

object ShoplistController extends Controller {
val shopForm = Form(
mapping(
  "id" -> number,
  "name" -> nonEmptyText,
  "describe"->nonEmptyText,
  "sub_resource" -> optional(text),
  "addId"->longNumber, 
  "recommand"->number, 
  "commentsum"->number, 
  "commentnumber"-> number,
  "userId"->number
)((Subject.apply _).tupled)(Subject.unapply)
)
}

错误是:

[info] Compiling 2 Scala sources to C:testprojectsslickplaytargetscala-2.10
classes...
[error] C:testprojectsslickplayappcontrollersShoplistController.scala:23: t
ype mismatch;
[error]  found   : (Int, String, String, String, Long, Int, Int, Int, Int) => mo
dels.Web.Subject
[error]  required: (Int, String, String, Option[String], Long, Int, Int, Int, In
t) => ?
[error]     )(Subject.apply )(Subject.unapply)
[error]               ^
[error] one error found
[error] (compile:compile) Compilation failed

如何编写这种映射方法?对于slick2和playframework2,有没有数据映射到Form的例子?

如您所见,Form要求您提供Mapping,因此它应该是"id" -> number,而不是"id" -> Int

UPD:你的Subjectsub_resource被定义为String,但你的映射说它是optional(text),意思是Option[String]

您应该将Subject模型更改为case class Subject(id: Int, name:String, describe: String, sub_resource:Option[String]....,或者将映射替换为"sub_resource" -> text

最新更新