每个文件有1个Slick表类和外键定义

时间:2014-07-05 18:04:15

标签: scala slick

我正在看Slick 2.0

this tutorial中,架构如下:

// Definition of the SUPPLIERS table
class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
  def id = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
  def name = column[String]("SUP_NAME")
  def street = column[String]("STREET")
  def city = column[String]("CITY")
  def state = column[String]("STATE")
  def zip = column[String]("ZIP")
  // Every table needs a * projection with the same type as the table's type parameter
  def * = (id, name, street, city, state, zip)
}
val suppliers = TableQuery[Suppliers] //Definition TableQuery for suppliers

// Definition of the COFFEES table
class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
  def name = column[String]("COF_NAME", O.PrimaryKey)
  def supID = column[Int]("SUP_ID")
  def price = column[Double]("PRICE")
  def sales = column[Int]("SALES")
  def total = column[Int]("TOTAL")
  def * = (name, supID, price, sales, total)
  // A reified foreign key relation that can be navigated to create a join
  def supplier = foreignKey("SUP_FK", supID, suppliers)(_.id) // Supplier defined above
}
val coffees = TableQuery[Coffees]

此处,TableQuery[Suppliers]的定义在与Coffee定义相同的文件中完成,因此我们可以为foreignKey(TableQuery)<提供supplier / p>

现在,我想将每个班级保留在一个文件中,并在我需要的时候创建TableQuery

我的问题是:

我应该如何定义Coffee类中的外键并将Suppliers类保存在单独的文件中?

我是否必须在Scala对象中创建TableQuery并将其导入Suppliers类,以便我可以为foreignKey定义提供TableQuery

我希望我很清楚:/

谢谢

1 个答案:

答案 0 :(得分:1)

您只需引用外键所关联的TableQuery

// SuppliersSchema.scala
object SuppliersSchema {

  class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
    /* Omitted for brevity */
  }
  val suppliers = TableQuery[Suppliers] //Definition TableQuery for suppliers
}

// CoffeesSchema.scala
object CoffeesSchema {
  class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
    /* Omitted for brevity */

    def supplier = foreignKey("SUP_FK", supID, SuppliersSchema.suppliers)(_.id) // define in another file
  }

  val coffees = TableQuery[Coffees]
}

另一种方法是在TableQuery内创建对Suppliers的{​​{1}}引用,并在外键定义键中使用它,无论如何这种方法未经测试,因为我个人更喜欢第一个之一。