Yevgen
Yevgen

Reputation: 4729

How to create model with foreign key in slick?

JVM requires case class of model with foreign key to be:

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

And in this case instead of address object it will be only id in json.

To generate JSON with internal address object it should be like:

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

And in this case code does not compile. How should class Cusomers look like to make it work properly?

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

Upvotes: 2

Views: 1098

Answers (1)

vdebergue
vdebergue

Reputation: 2414

With Slick, your table class should represent your sql table, so I would keep the Customers class as you wrote it. In my DAO, I would have a method:

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

To generate JSON, you can write a json.Writes[(Customer, Address)] or a method:

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

Upvotes: 2

Related Questions