2015-11-06 87 views
2

JVM需要的情況下類模型與外鍵是:如何用浮動的外鍵創建模型?

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) 
    } 

回答

2

用油滑,你的表類應該代表你的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) 
)