如何在光滑中创建带外键的模型?

时间:2015-11-06 22:01:03

标签: json scala playframework slick

JVM要求使用外键的case类型为:

case class Customer(id: Option[Int], name: String, surname: Option[String], gender: Option[String], addressId: Int)

在这种情况下,而不是地址对象,它将只是json中的id。

要使用内部地址对象生成JSON,它应该是:

case class Customer(id: Option[Int], name: String, surname: Option[String], gender: Option[String], address: Address)

在这种情况下代码无法编译。类Cusomers应该如何使其正常工作?

class Customers(tag: Tag) extends Table[Customer](tag, "customer"){
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def name = column[String]("name")
    def surname = column[String]("surname")
    def gender = column[String]("gender")
    def addressId = column[Int]("address_id")
    def * = (id.?, name, surname.?, gender.?, addressId) <> ((Customer.apply _).tupled, Customer.unapply)
    def address = foreignKey("address",addressId,addresses)(_.id)
  }

1 个答案:

答案 0 :(得分:2)

使用Slick,您的表类应该代表您的sql表,因此我会在您编写它时保留Customers类。 在我的DAO中,我会有一个方法:

def findCustomersWithAddress(): List[(Customer, Address)] = {
    for {
       customer <- customers
       address <- adresses if customer.addressId = address.id
    } yield (customer -> adress)
}.list

要生成JSON,您可以编写json.Writes[(Customer, Address)]或方法:

def toJson(customer: Customer, address: Address): JsObject = Json.obj(
  ...,
  "address" -> Json.toJson(address)
)