[英]create a class Table for an inexisting table slick scala (Slick 3.0.0, scala)
假設我們有一個數據庫,其中包含兩個表: Coffee
和Suppliers
,並且具有相應的案例類和表,就像在文檔中一樣:
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
}
當我們編寫聯接時,我們可以寫類似的東西(以便我們可以將結果轉換為Joined類型):
val result = for {
c <- coffees
s <- suppliers if c.supID === s.id
} yield (c.name, s.name).as(Joinds)
謝謝。
您可以像這樣定義它嗎:
val result = for {
c <- coffees
s <- suppliers if c.supID === s.id
} yield Joined(c.name, s.name)
並把它塞進一些方便的地方?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.