如何使选项[Int]保存在scala slick中
我想用用户的foreignkey保存ressource如何使选项[Int]保存在scala slick中,scala,slick,Scala,Slick,我想用用户的foreignkey保存ressource 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.u
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 _)
}
case类用户(id:Option[Int],name:String)
对象用户扩展表[用户](“用户”){
def id=列[Int](“id”,O.PrimaryKey)
def name=列[字符串](“名称”,O.NotNull)
def*=id.?~名称(用户,用户.未应用)
def add(用户:用户)(隐式会话:会话)={
此。插入(用户)
}
def countByName(名称:字符串)(隐式会话:会话)={
(用于{
用户您的资源
案例类与您的资源
对象不匹配。您的Int,String,String
与具有Long,Int,String
的伴生对象匹配。将资源
更改为:
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)
}
另外,我建议将所有选项[Int]
案例类id值更改为选项[Long]
,以匹配您的对象
更新:
正如user@cvogt所提到的,在投影中的可选字段上还需要一个?
,如下所示:
def * = id.? ~ owner ~ types <> (Resource, Resource.unapply _)
def*=id.?~owner~类型(Resource,Resource.unapply)
我将资源更改为案例类资源(id:Option[Long]=None,owner:Int,types:String)错误仍然存在为什么?将添加到id中?
我更改了答案
def * = id.? ~ owner ~ types <> (Resource, Resource.unapply _)