【问题标题】:create a class Table for an inexisting table slick scala (Slick 3.0.0, scala)为不存在的表 slick scala (Slick 3.0.0, scala) 创建一个类 Table
【发布时间】:2015-07-10 08:58:59
【问题描述】:

假设我们有一个包含两个表的数据库:CoffeeSuppliers,并且我们有它们对应的案例类和表,就像在文档中一样:

import scala.slick.driver.MySQLDriver.simple._
import scala.slick.lifted.{ProvenShape, ForeignKeyQuery}


// A Suppliers table with 6 columns: id, name, street, city, state, zip
class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
  def id: Column[Int] = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
  def name: Column[String] = column[String]("SUP_NAME")
  def street: Column[String] = column[String]("STREET")
  def city: Column[String] = column[String]("CITY")
  def state: Column[String] = column[String]("STATE")
  def zip: Column[String] = column[String]("ZIP")

  // Every table needs a * projection with the same type as the table's type parameter
  def * : ProvenShape[(Int, String, String, String, String, String)] = (id, name, street, city, state, zip)
}

// A Coffees table with 5 columns: name, supplier id, price, sales, total
class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
  def name: Column[String] = column[String]("COF_NAME", O.PrimaryKey)
  def supID: Column[Int] = column[Int]("SUP_ID")
  def price: Column[Double] = column[Double]("PRICE")
  def sales: Column[Int] = column[Int]("SALES")
  def total: Column[Int] = column[Int]("TOTAL")

  def * : ProvenShape[(String, Int, Double, Int, Int)] = (name, supID, price, sales, total)

  // A reified foreign key relation that can be navigated to create a join
  def supplier: ForeignKeyQuery[Suppliers, (Int, String, String, String, String, String)] = 
    foreignKey("SUP_FK", supID, TableQuery[Suppliers])(_.id)
}

现在假设我们要进行连接:

   val result = for {
       c <- coffees
       s <- suppliers if c.supID === s.id
} yield (c.name, s.name)

这里处理结果很复杂(如果我们有很多连接,那就更复杂了)因为我们需要始终记住名称的顺序,知道_._1_._2 指的是什么...等等

问题 1 有没有办法将结果的类型更改为包含所需列的新类的表?

问题2这里有一个方法但是我做不完,我们构造一个case类例如:

case class Joined(nameS: String,nameC: String)

然后我们构造对应的表,我不知道如何

class Joineds extends Table[Joinedclass] {
//Todo
}

当我们写一个 join 时,我们可以写类似 ( 这样我们就可以将 result 转换为 Joined 类型) :

   val result = for {
       c <- coffees
       s <- suppliers if c.supID === s.id
} yield (c.name, s.name).as(Joinds)

谢谢。

【问题讨论】:

    标签: database scala slick slick-3.0


    【解决方案1】:

    你能这样定义吗:

    val result = for {
      c <- coffees
      s <- suppliers if c.supID === s.id
    } yield Joined(c.name, s.name)
    

    然后把它藏在方便的地方?

    【讨论】:

    • 谢谢你的回答,我用另一种方式解决了这个问题,但实际上你的例子很有趣,result 的类型是Seq[Joined]?
    • 运行查询并等待未来完成后,您将能够获得 Seq[Joined],是的。很高兴听到你解决了它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 2016-02-29
    • 2015-10-29
    • 1970-01-01
    相关资源
    最近更新 更多