2015-07-10 47 views
0

假設我們有一個包含兩個表的數據庫:CoffeeSuppliers,我們有它們相應的大小寫表和表格,就像在文檔中一樣:創建一個不存在的表格浮動scala(Slick 3.0.0,scala)

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 class Joined(nameS: String,nameC: String) 

後,我們構造相應的表,我不知道如何

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

,當我們書寫一個連接,我們可以寫類似(這樣我們就可以改變結果的類型也參加):

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

謝謝。

回答

1

您可以定義它像:

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

而且將它保存起來有些不方便的地方?

+0

謝謝你的回答,我以另一種方式解決了這個問題,但實際上你的例子很有趣,'result'的類型是'Seq [Joined]'? – Elaqqad

+0

在運行查詢並等待未來完成後,您將能夠獲得Seq [加入],是的。很高興聽到你解決它! – Rikard

相關問題