我想用用户的外键保存Rescource
case class User(id: Option[Int], name : String)
object Users extends Table[User]("users") {
def id = column[Int]("id", O.PrimaryKey)
def name = column[String]("name", O.NotNull)
def * = id.? ~ name <> (User, User.unapply _)
def add(user: User)(implicit session: Session) = {
this.insert(user)
}
def countByName(name: String)(implicit session: Session) = {
(for {
user <- Users
if (user.name === name)
} yield(user)).list.size
}
}
case class Resource(id: Option[Long] = None, owner: Int, types: String)
object Resources extends Table[Resource]("RESOURCE") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def owner = column[Int]("Owner")
def types = column[String]("Type")
def withuser = foreignKey("User_FK", owner, Users)(_.id)
// Every table needs a * projection with the same type as the table's type parameter
def * = id ~ owner ~ types <> (Resource, Resource.unapply _)
}
编译错误时是:
[error] F:\mysource\play-slick\app\models\Resource.scala:17: overloaded method v
alue <> with alternatives:
[error] [R(in method <>)(in method <>)(in method <>)(in method <>)(in method <
>)(in method <>)(in method <>)(in method <>)](f: (Long, Int, String) => R(in met
hod <>)(in method <>)(in method <>)(in method <>)(in method <>)(in method <>)(in
method <>)(in method <>), g: R(in method <>)(in method <>)(in method <>)(in met
hod <>)(in method <>)(in method <>)(in method <>)(in method <>) => Option[(Long,
Int, String)])scala.slick.lifted.MappedProjection[R(in method <>)(in method <>)
(in method <>)(in method <>)(in method <>)(in method <>)(in method <>)(in method
<>),(Long, Int, String)] <and>
[error] [R(in method <>)(in method <>)(in method <>)(in method <>)(in method <
>)(in method <>)(in method <>)(in method <>)](f: ((Long, Int, String)) => R(in m
ethod <>)(in method <>)(in method <>)(in method <>)(in method <>)(in method <>)(
in method <>)(in method <>), g: R(in method <>)(in method <>)(in method <>)(in m
ethod <>)(in method <>)(in method <>)(in method <>)(in method <>) => Option[(Lon
g, Int, String)])scala.slick.lifted.MappedProjection[R(in method <>)(in method <
>)(in method <>)(in method <>)(in method <>)(in method <>)(in method <>)(in meth
od <>),(Long, Int, String)]
[error] cannot be applied to (models.Resource.type, models.Resource => Option[(
Option[Long], Int, String)])
[error] def * = id ~ owner ~ types <> (Resource, Resource.unapply _)
[error] ^
我认为这是串行选项[Int]的问题,任何人都知道如何保存Option [Int]
答案 0 :(得分:1)
您的Resource
案例类与您的Resources
对象不匹配。您Int, String, String
与具有Long, Int, String
的随播广告对象匹配。将Resources
更改为:
object Resources extends Table[Resource]("RESOURCE") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def owner = column[String]("Owner")
def types = column[String]("Type")
def withuser = foreignKey("User_FK", owner, Users)(_.id)
}
此外,我建议您将所有Option[Int]
案例类ID值更改为Option[Long]
,以匹配您的对象。
<强>更新强>
正如用户@cvogt所提到的,您还需要投影中可选字段.?
,如下所示:
def * = id.? ~ owner ~ types <> (Resource, Resource.unapply _)